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

Python 从两个列表开始,如何将每个列表中相同索引的元素放入元组列表中,python,indexing,tuples,Python,Indexing,Tuples,考虑两个列表,每个列表包含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个元组列表如下所示:

考虑两个列表,每个列表包含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)
您可以使用创建元组列表,然后使用列表删除其中没有的条目

[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')]

这将跳过第二个列表中对应项为
None
的配对:

final_list_of_tuples = [(a, b) for (a, b) in zip(list_one, list_two) if b is not None]
对于循环版本,这里有一个可能的

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))

你可以通过滚动两个列表的索引来实现,因为它们的大小相同,试试这个

for x in range(len(list_two)):
    if list_two[x] == None:
        pass
    else:
        e = (list_two[x],list_one[x])
        final_list_of_tuples.append(e)               
print(final_list_of_tuples)

你的意思是:
print(list(zip(list\u-one,list\u-two))
?否-这不会忽略我的None值。在这种情况下:
list(filter(lambda x:x[1],zip(list\u-one,list\u-two))
我在键入我的答案时,你的答案弹出并停止=)决定在删除你的答案后发布。我喜欢第二种解决方案,主要是因为它与我所尝试的最接近。我还没有了解zip函数是如何工作的,所以我将坚持我所知道的。谢谢我最喜欢的答案是:)
for x in range(len(list_two)):
    if list_two[x] == None:
        pass
    else:
        e = (list_two[x],list_one[x])
        final_list_of_tuples.append(e)               
print(final_list_of_tuples)