简体   繁体   中英

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:

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:

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:

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.

[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 :

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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