Python列表字典理解

发布于 2024-10-22 22:07:34 字数 417 浏览 4 评论 0原文

我有一些“列表”,其中包含一些词典 - 比如说 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨后彩虹 2024-10-29 22:07:34

首先将列表转换为字典

d = [dict(itertools.chain(*(d.iteritems() for d in a)))
     for a in [lstone, lsttwo]]

接下来构建转置列表:

keys = d[0].keys()
transposed = [[e[k] for k in keys] for e in d]

最后,转置并使用 csv.writer 将其写入文件:

with open("a.csv", "wb") as f:
    csv.writer(f).writerows(zip(keys, *transposed))

First convert your list to dictionaries

d = [dict(itertools.chain(*(d.iteritems() for d in a)))
     for a in [lstone, lsttwo]]

Next build the transposed list:

keys = d[0].keys()
transposed = [[e[k] for k in keys] for e in d]

Finally, transpose and use csv.writer to write this to a file:

with open("a.csv", "wb") as f:
    csv.writer(f).writerows(zip(keys, *transposed))
如痴如狂 2024-10-29 22:07:34

您确定输入数据不能用 2 元组而不是字典来表示吗?

如果答案是否定的,那么我迄今为止看到的其他解决方案将无法适用于所有可能的情况,例如字典中具有多个条目的输入项。这一个将:

from collections import defaultdict
lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]

# merge
merge = defaultdict(list)
for e in lstone + lsttwo:
    for k, v in e.items():
        merge[k].append(v)
# flatten
result = [ [k] + v for k, v in merge.items()] 
print result
# your option as to how to convert to CSV

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:

from collections import defaultdict
lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}]
lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}]

# merge
merge = defaultdict(list)
for e in lstone + lsttwo:
    for k, v in e.items():
        merge[k].append(v)
# flatten
result = [ [k] + v for k, v in merge.items()] 
print result
# your option as to how to convert to CSV
沉溺在你眼里的海 2024-10-29 22:07:34

这是创建列表的方法:

def makeLists(*lists):
    for dicts in zip(*lists):
        key = dicts[0].iterkeys().next()
        yield [key] + [d[key] for d in dicts]

newlistone, newlisttwo, newlistthree = makeLists(lstone, lsttwo)

此代码假设每个列表包含相同数量的字典,并且相应的字典恰好包含具有相同键的条目。

要将其全部写入文件,请使用以下命令:

with open("test.txt", "w") as file:
    file.write(",".join(newlistone) + "\n")
    # other lines individually

您还可以将所有列表放入一个列表中,并在写入文件时循环遍历它们。

This is how you can create the lists:

def makeLists(*lists):
    for dicts in zip(*lists):
        key = dicts[0].iterkeys().next()
        yield [key] + [d[key] for d in dicts]

newlistone, newlisttwo, newlistthree = makeLists(lstone, lsttwo)

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:

with open("test.txt", "w") as file:
    file.write(",".join(newlistone) + "\n")
    # other lines individually

You can also put all lists in one list and loop over them when writing to the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文