Skip to main content
 首页 » 编程设计

python之在迭代到 .append() 元素期间创建新的列表名称

2025年05月04日26haluo1

I am trying to create new list_names during an Iteration that I can add Elements to.

# input 
df = pd.DataFrame({"R1": [8,2,3], "R2": [-21,-24,4], "R3": [-9,46,6]}) 

# desired Output 
list1 = df.values[0].tolist() 
print(list1) 
list2 = df.values[1].tolist() 
print(list2) 
list3 = df.values[2].tolist() 
print(list3) 

# failed attempt 
for i in range(3): 
    print(f'{"list"}{i}') = df.values[i].tolist() 

请您参考如下方法:

您无需迭代即可处理整个数据框。访问底层数组并将其一次性转换为列表列表。

import pandas as pd 
df = pd.DataFrame({"R1": [8,2,3], "R2": [-21,-24,4], "R3": [-9,46,6]}) 
 
#out = df.to_numpy().tolist() for pandas >0.24 
out = df.values.tolist() 
print(out) 
print(out[0]) 
print(out[1]) 
print(out[2]) 

输出:

[[8, -21, -9], [2, -24, 46], [3, 4, 6]] 
[8, -21, -9] 
[2, -24, 46] 
[3, 4, 6] 

以这种方式,您可以使用 out 变量作为您想要的所有单独列表的集合。


如果您希望使用字典,您也可以按如下方式创建它:

out_dict = {f"list{i}":lst for i, lst in enumerate(out, start=1)} 
#Output: 
{'list1': [8, -21, -9], 'list2': [2, -24, 46], 'list3': [3, 4, 6]} 
 
print(out_dict['list1']) 
print(out_dict['list2']) 
print(out_dict['list3']) 

在列表和字典方法之间,您应该能够涵盖您真正需要的所有用例。尝试动态创建可变数量的变量通常不是一个好主意。 Related read