Python迭代生成新的空变量

Python迭代生成新的空变量,python,loops,Python,Loops,假设df1到df10是新变量,并且没有分配任何值。有没有可能写一个For循环来生成所有的空值?我可以生成字符串,但不能生成新变量 列表=[df1、df2、df3、df4、df5、df6、df7、df8、df9、df10]以下是通过词典理解实现这一点的方法: import pandas as pd d = {f'df{n+1}':pd.DataFrame() for n in range(10)} print(d) 输出: {'df1': Empty DataFrame Co

假设df1到df10是新变量,并且没有分配任何值。有没有可能写一个For循环来生成所有的空值?我可以生成字符串,但不能生成新变量


列表=[df1、df2、df3、df4、df5、df6、df7、df8、df9、df10]

以下是通过词典理解实现这一点的方法:

import pandas as pd

d = {f'df{n+1}':pd.DataFrame() for n in range(10)}

print(d)
输出:

{'df1': Empty DataFrame
        Columns: []
        Index: [],
 'df2': Empty DataFrame
        Columns: []
        Index: [],
 'df3': Empty DataFrame
        Columns: []
        Index: [],
 'df4': Empty DataFrame
        Columns: []
        Index: [],
 'df5': Empty DataFrame
        Columns: []
        Index: [],
 'df6': Empty DataFrame
        Columns: []
        Index: [],
 'df7': Empty DataFrame
        Columns: []
        Index: [],
 'df8': Empty DataFrame
        Columns: []
        Index: [],
 'df9': Empty DataFrame
        Columns: []
        Index: [],
 'df10': Empty DataFrame
        Columns: []
        Index: []}
Empty DataFrame
Columns: []
Index: []
如果必须将它们存储在变量中:

import pandas as pd

d = []
for n in range(10):
    locals()[f'df{n+1}'] = pd.DataFrame()
    d.append(locals()[f'df{n+1}'])
现在,您可以通过调用数据帧的变量名来访问它们:

print(df1)
输出:

{'df1': Empty DataFrame
        Columns: []
        Index: [],
 'df2': Empty DataFrame
        Columns: []
        Index: [],
 'df3': Empty DataFrame
        Columns: []
        Index: [],
 'df4': Empty DataFrame
        Columns: []
        Index: [],
 'df5': Empty DataFrame
        Columns: []
        Index: [],
 'df6': Empty DataFrame
        Columns: []
        Index: [],
 'df7': Empty DataFrame
        Columns: []
        Index: [],
 'df8': Empty DataFrame
        Columns: []
        Index: [],
 'df9': Empty DataFrame
        Columns: []
        Index: [],
 'df10': Empty DataFrame
        Columns: []
        Index: []}
Empty DataFrame
Columns: []
Index: []

使用字典使用口述或列表谢谢回复。在代码中,df1是字典的键,而不是变量。printdf1不起作用。您仍然可以执行printd['df1']。请参阅我编辑的文章。