簡體   English   中英

將元組組合成一個列表

[英]Combining Tuples into a List

我有一個元組列表:

[(1,2), (5,10), (2,5)]

我想得到一個唯一號碼的列表

[1,2,5,10]

我可以知道我怎樣才能做到這一點嗎?

您可以使用 numpy 這樣做:

import numpy as np

x = [(1,2),(5,10),(2,5)]
result = np.array(x).reshape(-1)

如果要獲取唯一值,請像這樣使用set()

result = set(np.array(x).reshape(-1))
import itertools

L = [(1,2), (5,10), (2,5)]

flat_no_dupes = set(itertools.chain.from_iterable(L))

使用來自 iterable 的 itertools 鏈來展平列表,並設置一組來刪除重復項。

這行得通嗎? 我已將每個項目附加到一個新列表中,然后使用set()獲取唯一項目

new_lis = []
lis = [(1,2),(5,10),(2,5)]
for x,y in lis:
    new_lis.append(x)
    new_lis.append(y)
    
result = list(set(new_lis))

[1, 2, 10, 5]

單線解決方案:

tuples_list = [(1,2), (5,10), (2,5)]
res = sorted(list(set(sum(tuples_list, ()))))

我強烈建議您使用集合推導來實現此結果。 集合推導遍歷元組,然后遍歷每個元組中的值。 我們從這些值y構建一個集合。

a = [(1,2), (5,10), (2,5)]
{y for x in a 
   for y in x}
# {1, 2, 10, 5}

尊重插入順序的版本:

[(1,2), (5,10),(2,5)] -> [1, 2, 5, 10]

[(5,10), (2,5), (1,2)] -> [5, 10, 2, 1]

l = [(5,10),(2,5), (1,2)]

# flat list
l_flat = [i for pair in l for i in pair]

# dictionary of value-position pairs (1st occurence only)
d = dict.fromkeys(l_flat, None)
for i, v in enumerate(l_flat):
    if d[v] is not None:
        continue
    d[v] = i

# order per position and get values
res = [k for k, _ in sorted(d.items(), key=lambda p: p[1])]

# check result
print(res)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM