考虑两个列表,每个列表有 10 个元素:
list_one = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
list_two = ['ok', 'good', None, 'great', None, None, 'amazing', 'terrible', 'not bad', None]
如何创建一个元组列表,其中列表中的每个元组都包含每个列表中相同索引的两个元素——而且,我需要跳过 None 值,所以我最终的 6 个元组列表应该如下所示:
final_list_of_tuples = [('a', 'ok'), ('b', 'good'), ('d', 'great'), ('g', 'amazing'), ('h', 'terrible'), ('i', 'not bad')]
我尝试了以下代码,但它将 list_one 中的每个字符串都放入一个包含 list_two 中所有字符串的元组中:
final_list_of_tuples = []
for x in list_one:
for y in list_two:
if y == None:
pass
else:
e = (x,y)
final_list_of_tuples.append(e)
这会跳过第二个列表中对应项目的对None
:
final_list_of_tuples = [(a, b) for (a, b) in zip(list_one, list_two) if b is not None]
这是一种可能的for
循环版本:
final_list_of_tuples = []
for i, b in enumerate(list_two):
if b is not None:
a = list_one[i]
final_list_of_items.append((a, b))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句