简体   繁体   中英

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.

# 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.


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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