我需要创建一个从两个列表开始的列表:
list_one = [1, 2, 3]
list_two = [('foo', 2), ('bar', 3), ('oof', 2), ('rab', 5)]输出列表应该由在list_one中找到第二个元素的元组组成。
例如。
[('foo', 2), ('bar', 3), ('oof', 2)]我想到的愚蠢和(我认为)低效的方式:
for i in list_one:
for j in list_two:
if i == j[1]:
final_list.append(j)有没有建议一个有效的版本(考虑更大的列表)?
发布于 2022-05-04 13:41:12
您可以使用列表理解。
>>> list_one = [1, 2, 3]
>>>
>>> list_two = [('foo', 2), ('bar', 3), ('oof', 2), ('rab', 5)]
>>>
>>> list_one_unique_elements = set(list_one)
>>> [(first, second) for first, second in list_two if second in list_one_unique_elements]
[('foo', 2), ('bar', 3), ('oof', 2)]发布于 2022-05-04 13:40:57
Python为检查元素是否为in (列表)提供了简洁的语法:
result = []
for pair in list_two:
_, value = pair
if value in list_one:
result.append(tuple)https://stackoverflow.com/questions/72113937
复制相似问题