从两个列表开始,如何将每个列表中相同索引的元素放入一个元组列表中

2024-06-16 13:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑两个列表,每个列表有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)

Tags: ofnone元素列表okonelistfinal
3条回答

这将跳过第二个列表中对应项为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))
>>> filter(all, zip(list_one, list_two))
[('a', 'ok'), ('b', 'good'), ('d', 'great'), ('g', 'amazing'), ('h', 'terrible'), ('i', 'not bad')]

可以使用zip function创建元组列表,然后使用列表理解删除其中没有元组的条目。你知道吗

[w for w in zip(list_one, list_two) if None not in w]

输出:

[('a', 'ok'), ('b', 'good'), ('d', 'great'), ('g', 'amazing'), ('h', 'terrible'), ('i', 'not bad')]

相关问题 更多 >