简体   繁体   English

在迭代过程中为.append()元素创建新的列表名称

[英]Creating new list names during iteration to .append() elements

I am trying to create new list_names during an Iteration that I can add Elements to. 我正在尝试添加元素的迭代过程中创建新的list_names。

# 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()

失败的尝试

You can work on the entire dataframe without iteration. 您可以在整个数据框架上工作而无需迭代。 Access the underlying array and convert it into a list of lists in one go. 一次访问底层数组并将其转换为列表列表。

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])

Output: 输出:

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

In this manner, you can use the out variable as a collection of all individual lists that you wanted. 通过这种方式,您可以将out变量用作所需的所有单个列表的集合。


If you wish to use a dictionary instead, you can also create that as follows: 如果您想改用字典,也可以如下创建:

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'])

Between the list and dict approaches, you should be able to cover all use-cases you really need. 在列表方法和字典方法之间,您应该能够涵盖您真正需要的所有用例。 It is generally a bad idea to try making a variable number of variables on the fly. 尝试动态制作可变数量的变量通常是一个坏主意。 Related read 相关阅读

for i in range(3):
    print('list{} = {}'.format(i, df.loc[i].values.tolist()))

Output 输出量

list0 = [8, -21, -9]
list1 = [2, -24, 46]
list2 = [3, 4, 6]

First, to answer your question, to dynamically create variables you can use exec() 首先,要回答您的问题,要动态创建变量,可以使用exec()

for i in range(3):
    exec("List%d=%s" % (i,df.values[i].tolist()))
print(List1)

Secondly, above is a bad practise . 其次,以上是一个坏习惯 This poses a security risk when the values are provided by external data (user input, a file or anything). 当值由外部数据(用户输入,文件或其他任何内容)提供时,这会带来安全风险。 So it's better avoid using it . 因此,最好避免使用它

You can always use dictionary in that you can use key value pairs to achieve the same objective (See other answers). 您可以随时使用的字典中,您可以使用key value对来达到同样的目的(见其他答案)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM