Python列表字典理解
我有一些“列表”,其中包含一些词典 - 比如说 3 个词典。 3个词典如下:
lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]
我如何创建新列表如下:
newlistone = ['dc_test',1,4]
newlisttwo = ['ac_test',2,5]
newlistthree = ['con_test',3,6]
我的目标是编写一个新的csv文件,使其显示如下:
dc_test,1,4
ac_test,2,5
con_test,3,5
I have a few 'list' containing few dictionaries- say 3 dicts.
3 dictionaries as follows:
lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]
How do i create new lists as follows:
newlistone = ['dc_test',1,4]
newlisttwo = ['ac_test',2,5]
newlistthree = ['con_test',3,6]
My objective is to write a new csv file, so that it shows as follows:
dc_test,1,4
ac_test,2,5
con_test,3,5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先将列表转换为字典
接下来构建转置列表:
最后,转置并使用 csv.writer 将其写入文件:
First convert your list to dictionaries
Next build the transposed list:
Finally, transpose and use
csv.writer
to write this to a file:您确定输入数据不能用 2 元组而不是字典来表示吗?
如果答案是否定的,那么我迄今为止看到的其他解决方案将无法适用于所有可能的情况,例如字典中具有多个条目的输入项。这一个将:
Are you sure the input data can't be represented with 2-tuples instead of dicts?
If the answer is no, then other solutions I've seen so far won't work for all possible cases, like an input item having more than one entry in the dict. This one will:
这是创建列表的方法:
此代码假设每个列表包含相同数量的字典,并且相应的字典恰好包含具有相同键的条目。
要将其全部写入文件,请使用以下命令:
您还可以将所有列表放入一个列表中,并在写入文件时循环遍历它们。
This is how you can create the lists:
This code assumes that each list contains the same number of dictionaries, and that corresponding dictionaries contain exactly on entry with the same key.
To write it all to a file use this:
You can also put all lists in one list and loop over them when writing to the file.