簡體   English   中英

如何生成包含幾個列表的所有可能加法和減法組合的列表字典

[英]How to generate a dictionary of lists containing all possible additive and subtractive combinations of a few lists

比如說我有一個字典,其中字符串名稱作為鍵,並作為值列出:

dict = {}
dict['L1'] = ['a', 'b', 'c', 'd']
dict['L2'] = ['d', 'e', 'f']

我想生成一個新字典,其中的鍵對應於列表,這些列表是子列表的所有加法或減法組合。 所以如果我們打印新字典中的每個子列表,這應該是結果。

print(newdict['L1'])
a b c d
print(newdict['L1 not L2'])
a b c
print(newdict['L1 or L2'])
a b c d e f 
print(newdict['L2'])
d e f
print(newdict['L2 not L1'])
e f

我不知道對鍵進行編碼的最有效方法是什么以及確定組合的最佳方法是什么,但實際添加或減去列表很容易。

看起來你想做集合操作,你可以用 python 集合來做:

d = {}   # or d = dict()
d['L1'] = ['a', 'b', 'c', 'd']
d['L2'] = ['d', 'e', 'f']

s1 = set(d['L1'])
s2 = set(d['L2'])

print(s1.union(s2))
# {'a', 'b', 'c', 'd', 'e', 'f'}
print(s1.symmetric_difference(s2))
# {'a', 'b', 'c', 'e', 'f'}
print(s1.intersection(s2))
# {'d'}
print(s1.difference(s2))
# {'a', 'b', 'c'}
print(s2.difference(s1))
# {'e', 'f'}

旁注:當你調用字典dict時,它會覆蓋內置dict object,你通常不想這樣做

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM