简体   繁体   English

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

[英]Starting from two lists, how to put the elements of the same index from each list into a list of tuples

Consider two lists, each with 10 elements: 考虑两个列表,每个列表包含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]

How can I create a list of tuples in which each tuple in the list contains two elements of the same index from each list -- but also, I need to skip the None values, so my final list of 6 tuples which should look like this: 我如何创建一个元组列表,其中列表中的每个元组都包含来自每个列表的相同索引的两个元素-而且,我需要跳过None值,所以我的最终6个元组列表应该看起来像这样:

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

I tried the following code, but it puts every single one of the strings from list_one into a tuple with all of the strings from list_two: 我尝试了以下代码,但是将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)

You can use zip function to create the list of tuples and then remove the entries with None in it using a list comprehension. 您可以使用zip函数创建元组列表,然后使用列表推导删除其中没有任何内容的条目。

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

Outputs: 输出:

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

This skips pairs where the corresponding item in the second list is None : 这将跳过第二个列表中对应项为None

final_list_of_tuples = [(a, b) for (a, b) in zip(list_one, list_two) if b is not None]

And here's one possible for loop version: 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')]

You could do it by scrolling through the indices of the two lists because they are the same size, try this... 您可以通过滚动浏览两个列表的索引来做到这一点,因为它们的大小相同,请尝试...

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM