我想从两个列表中有效地生成元素对,这些元素等于它们的笛卡尔积,并省略了一些元素。每个列表中的元素都是唯一的。
下面的代码完全满足了需要,但我希望通过替换循环来优化它。
详细内容请参见代码中的注释。
任何意见,将不胜感激。
from itertools import product
from pprint import pprint as pp
def pairs(list1, list2):
""" Return all combinations (x,y) from list1 and list2 except:
1. Omit combinations (x,y) where x==y """
tuples = filter(lambda t: t[0] != t[1], product(list1,list2))
""" 2. Include only one of the combinations (x,y) and (y,x) """
result = []
for t in tuples:
if not (t[1], t[0]) in result:
result.append(t)
return result
list1 = ['A', 'B', 'C']
list2 = ['A', 'D', 'E'] …Run Code Online (Sandbox Code Playgroud) 编辑:我已经更新了我的问题以澄清我的目标。
有没有办法通过使用reduce()或其他一些快速方法而不是for循环来加速这段代码?我查看了很多类似的问题,但没有找到答案。
old_dict = {'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'c', 'd']
new_dict = {}
for key in keys:
new_dict[key] = old_dict.get(key)
print(new_dict)
# prints:
# {'a': 1, 'c': 3, 'd': None}
Run Code Online (Sandbox Code Playgroud)