考虑两个列表,每个列表有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\u one中的每一个字符串与list\u 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
的配对:这里有一个可能的
for
循环版本:可以使用zip function创建元组列表,然后使用列表理解删除其中没有元组的条目。你知道吗
输出:
相关问题 更多 >
编程相关推荐