[英]Nested list comprehension on python
我是 python 的初學者,我想使用理解來創建字典。 假設我有以下兩個列表,並希望將它們轉換為字典,如{'Key 1':['c','d'], 'Key 2':['a','f'], 'Key 3':['b','e']}
。 我只能想到下面的代碼,我不知道如何使用理解來更改鍵和過濾器的值。 我應該如何更改我的代碼?
value = ['a','b','c','d','e','f']
key = [2, 3, 1, 1, 3, 2]
{"Key 1" : [value for key,value in list(zip(key,value)) if key==1]}
這應該這樣做:
value = ['a','b','c','d','e','f']
key = [2, 3, 1, 1, 3, 2]
answer = {}
for k, v in zip(key, value):
if k in answer:
answer[k].append(v)
else:
answer[k] = [v]
print(answer)
{2: ['a', 'f'], 3: ['b', 'e'], 1: ['c', 'd']}
編輯:哎呀,跳了槍。 道歉。
這是理解版本,但效率不高:
{
k: [v for i, v in enumerate(value) if key[i] == k]
for k in set(key)
}
編輯2:
這是一個具有更好復雜性的方法:
import pandas as pd
series = pd.Series(key)
{
k: [value[i] for i in indices]
for k, indices in series.groupby(series).groups.items()
}
你可以用字典理解和列表理解來做到這一點:
{f"Key {k}" : [value for key,value in zip(key,value) if key == k] for k in key}
您的列表將產生以下結果:
{'Key 2': ['a', 'f'], 'Key 3': ['b', 'e'], 'Key 1': ['c', 'd']}
按照要求。
使用 dict setdefault
value = ['a', 'b', 'c', 'd', 'e', 'f']
key = [2, 3, 1, 1, 3, 2]
d = {}
{d.setdefault(f'Key {k}', []).append(v) for k, v in zip(key, value)}
print(d)
輸出
{'Key 2': ['a', 'f'], 'Key 3': ['b', 'e'], 'Key 1': ['c', 'd']}
通常,它被寫成一個顯式循環(O(n) 解決方案):
>>> letters = 'abcdef'
>>> digits = [2, 3, 1, 1, 3, 2]
>>> from collections import defaultdict
>>> result = defaultdict(list) # digit -> letters
>>> for digit, letter in zip(digits, letters):
... result[digit].append(letter)
>>> result
defaultdict(<class 'list'>, {2: ['a', 'f'], 3: ['b', 'e'], 1: ['c', 'd']})
嵌套理解(O(nn) 解決方案)就像在其他答案中一樣:
>>> {
... digit: [letter for d, letter in zip(digits, letters) if digit == d]
... for digit in set(digits)
... }
{1: ['c', 'd'], 2: ['a', 'f'], 3: ['b', 'e']}
如果您需要將其寫為單個 dict itertools.groupby
,則可以使用itertools.groupby
(O(n log n) 解決方案):
>>> from itertools import groupby
>>> {
... digit: [letter for _, letter in group]
... for digit, group in groupby(
... sorted(zip(digits, letters), key=lambda x: x[0]),
... key=lambda x: x[0]
... )
... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.