简体   繁体   English

如何从 python 中的列表列表创建字典?

[英]How to create a dictionary from a list of lists in python?

Given a list of lists, how can I create a dictionary where the keys are all the items in the list (one copy), and the values are the number of times they are the first item in the list?给定一个列表列表,我如何创建一个字典,其中键是列表中的所有项目(一个副本),值是它们是列表中第一项的次数?

Given:鉴于:

[['banana', 'oranges', 'grapes'],['banana', 'grapes'],['grapes', 'oranges', 'banana']]

Expected:预期的:

{'banana': 2, 'grapes': 1, 'oranges': 0}

First get the list of first elements:首先获取第一个元素的列表:

filtered_list = [x[0] for x in initial_list]

And here are your unique elements:以下是您的独特元素:

unique_elements = set([y for x in initial_list for y in x])

Now initialize a dictionary with keys from unique elements and values of zero:现在使用来自唯一元素和零值的键初始化字典:

counts = {e: 0 for e in unique_elements}

Finally update the values of the dictionary with the frequencies of each element in the filtered list.最后用过滤列表中每个元素的频率更新字典的值。 Since you asked a solution without counter , here is a simple loop to achieve that:既然你问了一个没有counter的解决方案,这里有一个简单的循环来实现:

for i in filtered_list:
    counts[i] = counts.get(i, 0) + 1

print(counts)
# {'banana': 2, 'grapes': 1, 'oranges': 0}

You can use sets to get unique names present in the sub lists:您可以使用集合来获取子列表中存在的唯一名称:

initial_list = [['banana', 'oranges', 'grapes'],['banana', 'grapes'],['grapes', 'oranges', 'banana']]

unique = set()

for l in initial_list:
    unique = unique.union(set(l))

Then counting in how many list each item is present (assuming each item is either present or not, not duplicated):然后计算每个项目存在多少列表(假设每个项目存在或不存在,不重复):

from collections import defaultdict

result = defaultdict(lambda: 0)
for element in unique:
    for l in initial_list:
        result[element] += (element == l[0])

Defaultict is used to get an initial value of 0 And you should have your result in result Defaultict 用于获取初始值 0 你应该得到你的result

The fact that bool are a subclass of int is used to evaluate element == l[0] either to 1 or 0 boolint的子类这一事实用于将element == l[0]评估为10

Without collections you would need to edit the last line to be:如果没有collections ,您需要将最后一行编辑为:

try:
    result[element] += (element == l[0])
except KeyError:
    result[element] = 1

Create list of lists:创建列表列表:

ll = [['banana', 'oranges', 'grapes'], ['banana', 'grapes'], ['grapes', 'oranges', 'banana']]

Get unique keys:获取唯一键:

from itertools import chain

d = dict.fromkeys(chain(*ll), 0)

Count first elements of lists:计算列表的第一个元素:

from collections import Counter
from operator import itemgetter

c = Counter(map(itemgetter(0), ll))

Update and show result:更新并显示结果:

d.update(dict(c))
print(d)

Prints:印刷:

{'banana': 2, 'oranges': 0, 'grapes': 1}

All the previous responses failed for me.我之前的所有回复都失败了。 This is a very fast implementation that works:这是一个非常快速的实现:

# l is a list of lists
import itertools
ext_l = list(itertools.chain.from_iterable(l))
l_dic = {element:0 for element in set(ext_l)}
for i in ext_l: l_dic[i] += 1
print(l)

Simple implementation简单的实现

l = [['banana', 'oranges', 'grapes'],['banana', 'grapes'],['grapes', 'oranges', 'banana']]
unique_items = set([i for sl in l for i in sl])
d = dict()
for item in unique_items:
    d[item] = 0

for sublist in l:
    d[sublist[0]] += 1

print(d)
# output
# {'grapes': 1, 'oranges': 0, 'banana': 2}

To maintain order维持秩序

d = dict()
for sl in l:
    d[sl[0]] = d.get(sl[0],0) + 1
print(d)
# {'banana': 2, 'grapes': 1}

unique_items = set([i for sl in l for i in sl])
for item in unique_items:
    if item not in d:
        d[item] = 0
print(d)
# {'banana': 2, 'grapes': 1, 'oranges': 0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM