You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何先将字符串列表元素作为字符串操作再转为整数使用?

Solution: Use enumerate() to work with both strings and their corresponding integers

Absolutely, you can handle each string element first, then use its corresponding integer value (like its position in the NG list) in your code. The easiest way to do this is with Python's built-in enumerate() function—it lets you loop through the list and get both the integer index and the string element in each iteration.

Step-by-step breakdown:

  • enumerate(NG) returns pairs of (index, element) where index is the integer position (starting at 0 by default) and element is the string from NG (e.g., 'A', 'B', 'C').
  • If you need 1-based integers instead of 0-based, just add 1 to the index.
  • You can first run all your string-specific operations with the element, then use the integer index for whatever logic comes next.

Modified code example:

import pandas as pd 
import matplotlib.pyplot as plt 

NG = ['A','B','C'] 
l = [1,2,3,4,5,6] 
b = [6,5,4,3,2,1] 

# Initialize dflist outside the loop so it doesn't reset on each iteration!
dflist = [] 

for idx, n in enumerate(NG):
    # First, work with the string element
    print(f"Processing string: {n}")
    
    # Then get the corresponding integer (adjust to 1-based if needed)
    corresponding_int = idx + 1  # Gives 1 for 'A', 2 for 'B', 3 for 'C'
    print(f"Using integer: {corresponding_int}")
    
    # Your existing DataFrame operations (tweak as required)
    df = pd.DataFrame(l)
    dflist.append(df)
    
    df2 = pd.DataFrame(b)
    # ... add your remaining code using df2 or corresponding_int here

Alternative: Stick with range/len (if you prefer)

If you wanted to use your original range(len()) approach, you can still make it work by indexing NG to get the string element:

for idx in range(len(NG)):
    n = NG[idx]  # Fetch the string element using the integer index
    print(f"String element: {n}")
    corresponding_int = idx + 1  # Get the matching integer
    # ... rest of your logic here

Both methods work, but enumerate() is generally more readable and Pythonic for this use case.

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:09:31