簡體   English   中英

從包含元組的元素創建列表

[英]Create List from Elements of Tuples with Exclusion

我想從列表中的元組元素中列出項目,以使這些元素不屬於其他列表,而且我知道每個元組都包含列表中的一個元素,但我不希望它屬於還有一個不在該列表中的元素。 例如,

tuples = [(2,1), (1,4), (1,7), (3,10), (4,3)]
exclude = [1, 3]

我正在尋找清單

[2, 4, 7, 10]

這很容易在笨拙的for循環中完成,但似乎有一些使用Python函數或列表理解的方法。 有任何想法嗎?

其實不明白這個問題。 假設這可能是您想要的

>>>list(set([j for i in tuples for j in i if not j in exclude]))
[2, 4, 10, 7]

您在示例中忘記了4,代碼將返回:

>>>[num for tup in tuples for num in tup if num not in exclude]
[2, 4, 7, 10, 4]

假設您的要求是將元組列表轉換為列表,然后在列表中獲取唯一元素,將列表排除在外,然后對其進行排序。

from itertools import chain
tuples_final = sorted(list(set(chain(*tuples))-set(exclude)))

暫無
暫無

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

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