Python 列表理解或 lambda 可能适用于我给定的代码片段?
Python list comprehension or lambda possible for my given code snippet?
编辑:删除了未定义的变量。
所以我的代码基本上是,尝试比较一个列表的值是否存在于另一个列表中。如果是这样,将该值附加到第三个列表。如果该值不存在,则附加到第 4 个列表。执行此任务最有效和可读的方法是什么。我的代码示例:
a = [1,2,3]
b = [2,3,4,5,6,7]
c = []
d = []
for ele in a:
if ele in b:
c.append(ele )
else:
d.append(ele)
解决这个问题的最佳方法是使用集合。
import random
a = [random.randint(1, 15) for _ in range(5)]
b = [random.randint(1, 15) for _ in range(7)]
print(a)
print(b)
set_a = set(a)
set_b = set(b)
set_intersection = set_a.intersection(set_b)
set_diff = set_a.difference(set_b)
print(list(set_intersection))
print(list(set_diff))
c = [i for i in a if i in b]
d = [i for i in a if i not in b]
a=[2,3,4,5]
b=[3,5,7,9]
c = [value for value in a if value in b]
d = [value for value in a if value not in b]
print(f'Present in B: {c}')
print(f"Not present in B: {d}")
编辑:删除了未定义的变量。 所以我的代码基本上是,尝试比较一个列表的值是否存在于另一个列表中。如果是这样,将该值附加到第三个列表。如果该值不存在,则附加到第 4 个列表。执行此任务最有效和可读的方法是什么。我的代码示例:
a = [1,2,3]
b = [2,3,4,5,6,7]
c = []
d = []
for ele in a:
if ele in b:
c.append(ele )
else:
d.append(ele)
解决这个问题的最佳方法是使用集合。
import random
a = [random.randint(1, 15) for _ in range(5)]
b = [random.randint(1, 15) for _ in range(7)]
print(a)
print(b)
set_a = set(a)
set_b = set(b)
set_intersection = set_a.intersection(set_b)
set_diff = set_a.difference(set_b)
print(list(set_intersection))
print(list(set_diff))
c = [i for i in a if i in b]
d = [i for i in a if i not in b]
a=[2,3,4,5]
b=[3,5,7,9]
c = [value for value in a if value in b]
d = [value for value in a if value not in b]
print(f'Present in B: {c}')
print(f"Not present in B: {d}")