簡體   English   中英

如何從 python 中的列表列表創建字典?

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

給定一個列表列表,我如何創建一個字典,其中鍵是列表中的所有項目(一個副本),值是它們是列表中第一項的次數?

鑒於:

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

預期的:

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

首先獲取第一個元素的列表:

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

以下是您的獨特元素:

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

現在使用來自唯一元素和零值的鍵初始化字典:

counts = {e: 0 for e in unique_elements}

最后用過濾列表中每個元素的頻率更新字典的值。 既然你問了一個沒有counter的解決方案,這里有一個簡單的循環來實現:

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

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

您可以使用集合來獲取子列表中存在的唯一名稱:

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

unique = set()

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

然后計算每個項目存在多少列表(假設每個項目存在或不存在,不重復):

from collections import defaultdict

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

Defaultict 用於獲取初始值 0 你應該得到你的result

boolint的子類這一事實用於將element == l[0]評估為10

如果沒有collections ,您需要將最后一行編輯為:

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

創建列表列表:

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

獲取唯一鍵:

from itertools import chain

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

計算列表的第一個元素:

from collections import Counter
from operator import itemgetter

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

更新並顯示結果:

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

印刷:

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

我之前的所有回復都失敗了。 這是一個非常快速的實現:

# 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)

簡單的實現

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}

維持秩序

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