簡體   English   中英

從兩個列表開始,如何將每個列表中相同索引的元素放入元組列表

[英]Starting from two lists, how to put the elements of the same index from each list into a list of 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個元組列表應該看起來像這樣:

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)

您可以使用zip函數創建元組列表,然后使用列表推導刪除其中沒有任何內容的條目。

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

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

您可以通過滾動瀏覽兩個列表的索引來做到這一點,因為它們的大小相同,請嘗試...

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