Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何生成包含几个列表的所有可能的加法和减法组合的列表字典_Python_Dictionary - Fatal编程技术网

Python 如何生成包含几个列表的所有可能的加法和减法组合的列表字典

Python 如何生成包含几个列表的所有可能的加法和减法组合的列表字典,python,dictionary,Python,Dictionary,例如,假设我有一个字典,其中字符串名称作为键,列表作为值: 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

例如,假设我有一个字典,其中字符串名称作为键,列表作为值:

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
对象,您通常不想这样做

看起来您想进行set操作,您可以使用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
对象,您通常不想这样做

技巧是将字典中的数据转换为集合。集合具有所需的属性。诀窍是将数据从字典转换为集合。集合具有所需的属性。