循环以在Python中将多个列表追加到单个列表 [英] Loop to append multiple lists to a single list in Python
问题描述
在下面的代码中,行[8],行[9],...,行[27]每个都包含许多数字.我需要将row [8],row [9]等中的所有数字附加到stat_by_symbol中,作为stat_by_symbol中的单独列表.但是,下面的代码将所有数字附加在单个列表的所有行中.
In the following code, row[8], row[9], ..., row[27] each contain many numbers. I need all of the numbers in row[8], row[9], etc. to append to stat_by_symbol as separate lists within within stat_by_symbol. However, the code below appends all of the numbers across all rows within a single list.
作为我所需要的示例,如果我叫stat_by_symbol ['aaa'] [0],则应该从行[8]中提取数字列表.
As an example of what I need, if I called stat_by_symbol['aaa'][0], then I should get the list of numbers pulled from row[8].
我该如何解决?非常感谢.
How can I fix this? Many thanks.
编辑以进一步说明.我已经附上了csv的快照.我需要stat_by_symbol ['aaa'] [0]给我第i列下的所有数字.同样,具有索引1的stat_by_symbol将为我提供第j列下的所有数字.
EDIT for further clarification. I've attached a snapshot of the csv. I need stat_by_symbol['aaa'][0] to give me all of the numbers under Column i. Similarly, stat_by_symbol with index 1 would give me all of the numbers under Column j.
stat_by_symbol = {}
with open('zzdata.csv', 'rb') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for symbol in symbols:#symbols in a list
if symbol in row:
for i in range(8, 28):
stat_by_symbol.setdefault(symbol, []).append(row[i])
推荐答案
stat_by_symbol = dict((symbol, [[] for i in xrange(8,28)]) for symbol in symbols)
with open('zzdata.csv', 'rb') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for symbol, symbol_list in stat_by_symbol.iteritems():
if symbol in row:
for symbol_list2, cell in zip(symbol_list, row[8:28]):
symbol_list2.append(cell)
这篇关于循环以在Python中将多个列表追加到单个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!