我正在尝试从循环中创建多维列表,但是当为行和列输入新值时,所有列值会同时更改,导致仅保留最后一个值,这是某些事情。我知道它与我如何初始化列表有关,但是不确定如何修复它。
代码:
sellorderprices = ["Sellorderprice", 0, 1, 2, 3, 4, 5]
buyorderprices=["Buyorderprice", 10, 11, 21, 31, 41, 51]
days=["Days",150, 120, 90, 60, 30, 0]
export_data=[[None]*3]*(len(days))
for n in range (0, len(export_data)):
export_data[n][0]=days[n]
export_data[n][1]=buyorderprices[n]
export_data[n][2]=sellorderprices[n]
print(export_data)
这将打印[[0,51,5],[0,51,5],[0,51,5],[0,51,5],[0,51,5],[0,51 ,5],[0、51、5]]
答案 0 :(得分:0)
尝试:
export_data=[[None for i in range(3)] for i in range(len(days))]
答案 1 :(得分:0)
创建export_data
时引用的是同一列表
您可以通过将代码更改为
export_data = [[None]*3 for i in range(len(days))]
或者,您可以使用zip
做同样的事情
export_data = list(zip(days, buyorderprices, sellorderprices))
# [('Days', 'Buyorderprice', 'Sellorderprice'), (150, 10, 0), (120, 11, 1), (90, 21, 2), (60, 31, 3), (30, 41, 4), (0, 51, 5)]
或
export_data = [list(e) for e in zip(days, buyorderprices, sellorderprices)]
# [['Days', 'Buyorderprice', 'Sellorderprice'], [150, 10, 0], [120, 11, 1], [90, 21, 2], [60, 31, 3], [30, 41, 4], [0, 51, 5]]