[英]Write several list of lists in a csv columns in Python
I have a list of lists and need to write each of its elements in csv columns. 我有一个列表列表,需要在csv列中写入其每个元素。 Using the code below it outputs exactly what I want.
使用下面的代码,它输出的正是我想要的。
for row in izip_longest(*averages_, fillvalue = ['']):
writer.writerow(row[0] + row[1])
a sample line of row[0]: 第[0]行的样本行:
['0.000000', '0.000586', '0.005819', '0.011434', '0.052012', 0.000586118993]
Question: How can I replace the part (row[0] + row[1])
with a code with a variable in it so that it automatically adds any number of sub-lists (row[i] + row[i+1] + row[i+2]...)
in the main list? 问题:如何用包含变量的代码替换零件
(row[0] + row[1])
,以便它自动添加任意数量的子列表(row[i] + row[i+1] + row[i+2]...)
主列表中的(row[i] + row[i+1] + row[i+2]...)
?
If row is a list of lists, replace (row[0] + row[1])
with 如果row是列表列表,则将
(row[0] + row[1])
替换为
list(itertools.chain.from_iterable(row))
or 要么
[item for sublist in row for item in sublist]
You are flattening a lists of lists. 您正在展平列表列表。 I picked both of those from https://stackoverflow.com/a/952952/2823755
我从https://stackoverflow.com/a/952952/2823755都选择了两者
If I understand well what you want than the following should do the job : 如果我很了解您想要的东西,则可以执行以下操作:
writer.writerow(reduce(lambda x, y: x+y, row))
This work over all elements of row . 这适用于row的所有元素。 If you want to sum the first count elements you can try like that :
如果您想对第一个计数元素求和,可以这样尝试:
writer.writerow(reduce(lambda x, y: x+y, row[:count - 1]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.