Python:保存作为 for 循环输出的列表?

Python: Saving lists that are outputs of a for loop?

提问人:gclt22 提问时间:10/18/2023 更新时间:10/18/2023 访问量:51

问:

我在 Excel 电子表格中有许多列(所有不同的长度)要导入 Python,我想将这些列中的每一列都保存为 Python 中的命名列表。有相当多的列,所以我想使用for循环来实现这一点。我可以导入所有列并在每次迭代期间成功打印它们,但我无法弄清楚如何将这些列表保存在列的名称下?例如,从“1”列开始,我想得到一个名为“1”的列表,该列表由该列中的 20 个值组成。

如果这是一个非常简单的问题,或者有更好的方法,我深表歉意 - 我对 Python 还很陌生。

这是我到目前为止所得到的,它将列提取并打印为列表:

lists = 'SpreadsheetFilePath.xlsx'  
columns = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "6", "17", "18"]
    
All_Data = pd.read_excel(lists, sheet_name = 'Schedule')

for i in columns:
    newlist = All_Data[i].values.tolist()
    newerlist = [x for x in newlist if str(x) != 'nan']
    print(newerlist)

我基本上想在循环重复之前将 newerlist 保存在名为“1”的列表下。

提前致谢。

Python 列表 循环

评论

1赞 jarmod 10/18/2023
在 CS 中,这称为关联数组。它是一种数据结构,用于存储键/值对的集合。它允许您将键与值相关联。在您的情况下,键是列名,值是该特定列的列值的数组/列表。在 Python 中,您将使用字典

答:

3赞 Nikolay 10/18/2023 #1

也许使用列表字典,其中键是列名,值是列表:

values_by_column = {}
for i in columns:
    newlist = All_Data[i].values.tolist()
    newerlist = [x for x in newlist if str(x) != 'nan']
    values_by_column[i] = newerlist

print(values_by_column["1"])
print(values_by_column["2"])
2赞 Matt Smith 10/18/2023 #2

您应该使用一个字典,其中键是您的变量列表名称,例如“1”,附加到每个键的值是其列表。调整代码:

lists = 'SpreadsheetFilePath.xlsx'  
columns = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "6", "17", "18"]
    
All_Data = pd.read_excel(lists, sheet_name = 'Schedule')

# Initialise a dictionary
dict_of_lists = dict()

for i in columns:
    newlist = All_Data[i].values.tolist()
    newerlist = [x for x in newlist if str(x) != 'nan']
    # Assign the list for column i to the key i
    dict_of_lists[i] = newerlist

然后,您可以通过在字典中处理其键来访问每个列表,例如

list_for_col_1 = dict_of_lists["1"]

for row in list_for_col_1:
    print(row)

阅读一下词典的一般工作方式,你应该坐飞机。一般来说,每当你发现自己想做一些可能需要动态数量的变量或动态变量名称的事情时,字典会有所帮助