簡體   English   中英

刪除列表中的重復項

[英]Removing duplicates in list of lists

我有一個由列表組成的列表,每個子列表中都有4個項目(整數和浮點數)。 我的問題是我想刪除那些index = 1和index = 3與其他子列表匹配的子列表。

[[1, 2, 0, 50], [2, 19, 0, 25], [3, 12, 25, 0], [4, 18, 50, 50], [6, 19, 50, 67.45618854993529], [7, 4, 50, 49.49657024231138], [8, 12, 50, 41.65340802385248], [9, 12, 50, 47.80600357035001], [10, 18, 50, 47.80600357035001], [11, 18, 50, 53.222014760339356], [12, 18, 50, 55.667812693447615], [13, 12, 50, 41.65340802385248], [14, 12, 50, 47.80600357035001], [15, 13, 50, 47.80600357035001], [16, 3, 50, 49.49657024231138], [17, 3, 50, 49.49657024231138], [18, 4, 50, 49.49657024231138], [19, 5, 50, 49.49657024231138]]

例如,[7、4、50、49.49657024231138]和[18、4、50、49.49657024231138]在索引1和3處具有相同的整數。因此,我想刪除一個,而這無關緊要。

我看了一些代碼,這些代碼使我可以在單個索引的基礎上執行此操作。

def unique_items(L):
found = set()
for item in L:
    if item[1] not in found:
        yield item
        found.add(item[1])

我一直在使用此代碼,該代碼允許我刪除列表,但僅基於單個索引即可刪除(我還沒有完全理解代碼,但是它可以正常工作。)

因此,問題在於僅基於列表列表中index = 1和index = 3的重復值來刪除子列表。

如果需要比較(item[1], item[3]) ,請使用元組。 元組是可哈希化的類型,因此可以用作set成員或dict鍵。

def unique_items(L):
    found = set()
    for item in L:
        key = (item[1], item[3])  # use tuple as key
        if key not in found:
            yield item
            found.add(key)

這是使它起作用的方式:

def unique_items(L):
    # Build a set to keep track of all the indices we've found so far
    found = set()  
    for item in L:
        # Now check if the 2nd and 4th index of the current item already are in the set
        if (item[1], item[3]) not in found: 
            # if it's new, then add its 2nd and 4th index as a tuple to our set
            found.add((item[1], item[3])
            # and give back the current item 
            # (I find this order more logical, but it doesn't matter much)
            yield item

這應該工作:

from pprint import pprint

d = {}
for sublist in lists:
    k = str(sublist[1]) + ',' + str(sublist[3])
    if k not in d:
        d[k] = sublist
pprint(d.values())

暫無
暫無

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

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