检查值列表是否在另一个嵌套列表中 python 和 returns 匹配
check a list of values is in another nested list python and returns match
我有两个值列表
lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]
我想检查 lst_a
中的每个值是否都在 nested_lst_b
和 return 中匹配的值
预期产出:
output = [[701221,310522],[8868,1168478],[5272],[]]
我在下面编写了代码,但没有达到我的预期...
for x,y in zip(lst_a,nested_lst_b):
if x in y:
print(x,y)
>>>701221 [701221, 310522, 765272, 12343]
>>>5272 [83645, 5272]
谁能帮我解决这个问题?非常感谢
根据您的初步尝试,这是一种简单的方法:
lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]
a_in_b = []
for sub_lst_b in nested_lst_b:
a_in_sub = []
for el_a in lst_a:
if el_a in sub_lst_b:
a_in_sub.append(el_a)
a_in_b.append(a_in_sub)
print(a_in_b)
在这里,您遍历 nested_lst_b
的每个子列表,并检查 lst_a
中的任何元素是否在该子列表中。它遵循您的输出要求(嵌套列表对应于 nested_lst_b
.
否则,此类问题可能会使用集合来解决。
另一个解决方案是使用 set.intersection
,但它需要在数据类型之间进行一些转换。
print([list(set.intersection(set(lst_a), set(b))) for b in nested_lst_b])
[[310522, 701221], [8868, 1168478], [5272], []]
我有两个值列表
lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]
我想检查 lst_a
中的每个值是否都在 nested_lst_b
和 return 中匹配的值
预期产出:
output = [[701221,310522],[8868,1168478],[5272],[]]
我在下面编写了代码,但没有达到我的预期...
for x,y in zip(lst_a,nested_lst_b):
if x in y:
print(x,y)
>>>701221 [701221, 310522, 765272, 12343]
>>>5272 [83645, 5272]
谁能帮我解决这个问题?非常感谢
根据您的初步尝试,这是一种简单的方法:
lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]
a_in_b = []
for sub_lst_b in nested_lst_b:
a_in_sub = []
for el_a in lst_a:
if el_a in sub_lst_b:
a_in_sub.append(el_a)
a_in_b.append(a_in_sub)
print(a_in_b)
在这里,您遍历 nested_lst_b
的每个子列表,并检查 lst_a
中的任何元素是否在该子列表中。它遵循您的输出要求(嵌套列表对应于 nested_lst_b
.
否则,此类问题可能会使用集合来解决。
另一个解决方案是使用 set.intersection
,但它需要在数据类型之间进行一些转换。
print([list(set.intersection(set(lst_a), set(b))) for b in nested_lst_b])
[[310522, 701221], [8868, 1168478], [5272], []]