簡體   English   中英

從元組列表中刪除元組

[英]Removing a tuple from list of tuples

我有一個看起來像這樣的元組列表;

ListTuples = [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102'), ('192.168.1.100', '192.168.1.103'), ('192.168.1.103', '192.168.1.100')]

我想在元組的第一個元素與另一個元組的第二個元素匹配並且同時,元組的第二個元素與相同的其他元組的第一個元素匹配時刪除元組。 OutputList將如下所示;

OutputList = [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102')]

除了遍歷所有元組進行比較並保存到新的元組列表之外,還有沒有更簡單的方法可以做到這一點?

謝謝。

進行兩組設置:第一組具有原始元組,第二組具有已交換元素的元組。 然后取兩個集合的交集。 這些是要刪除的元組。 用除以下以外的所有元組創建一個新列表:

>>> ListTuples = [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102'), ('192.168.1.100', '192.168.1.103'), ('192.168.1.103', '192.168.1.100')]
>>> set1 = set(ListTuples)
>>> set2 = set((e2, e1) for e1, e2 in ListTuples)
>>> to_remove = set1 & set2
>>> to_remove
set([('192.168.1.103', '192.168.1.100'), ('192.168.1.100', '192.168.1.103')])
>>> NewList = [t for t in ListTuples if t not in to_remove]
>>> NewList
[('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102')]

這將是O(n),而搜索列表將是O(n ** 2)。

好吧,如果要相互比較元組,則必須遍歷它們,但是至少您可以使用帶有反向元素的臨時集以加快查找速度:

ListTuples = [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102'),
              ('192.168.1.100', '192.168.1.103'), ('192.168.1.103', '192.168.1.100')]

seen = set()
for element in ListTuples:
    if element in seen:
        seen.discard(element)
    else:
        seen.add(tuple(reversed(element)))
OutputList = [tuple(reversed(element)) for element in seen]

print(OutputList)  # [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102')]

它不會保持順序。

使用collections.Counter計數每個已排序的元組出現的次數,然后過濾出計數大於一的那些元組:

from collections import Counter

ListTuples = [('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102'), ('192.168.1.100', '192.168.1.103'), ('192.168.1.103', '192.168.1.100')]

counts = Counter(tuple(sorted(t)) for t in ListTuples)
OutputList = [k for k in counts if counts[k] == 1]

>>> OutputList
[('192.168.1.100', '192.168.1.101'), ('192.168.1.100', '192.168.1.102')]

請注意,這不會保留原始列表中項目的順序。 在這種情況下,我不知道這對您是否重要。

在對每個元組進行排序時,效率也有些低下,但是必須考慮到項目順序,並且在一般情況下,如果每個元組可以包含2個以上的元素,則對元組進行排序將是一種方法走。

您可以像這樣將其設置為單線:

OutputList = [k for k, count in Counter(tuple(sorted(t)) for t in ListTuples).items() if count == 1]

暫無
暫無

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

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