簡體   English   中英

子列表的唯一元素取決於子列表中的特定值

[英]Unique elements of sublists depending on specific value in sublist

我試圖從一個非常大且不一致的列表中選擇唯一的數據集 我的數據集 RawData 由不同長度的字符串項目組成。 有些項目出現多次,例如: ['a','b','x','15/30']比較項目的總是最后一個字符串:例如'15/30'

目標是:獲取一個列表:包含僅出現一次的項目的 UniqueData。 (我想保留訂單)

數據集:

RawData = [['a','b','x','15/30'],['d','e','f','g','h','20/30'],['w','x','y','z','10/10'],['a','x','c','15/30'],['i','j','k','l','m','n','o','p','20/60'],['x','b','c','15/30']]

我想要的解決方案數據集:

UniqueData = [['a','b','x','15/30'],['d','e','f','g','h','20/30'],['w','x','y','z','10/10'],['i','j','k','l','m','n','o','p','20/60']]

我嘗試了許多可能的解決方案,例如:

for index, elem in enumerate(RawData):並附加到新列表中,如果.....

for element in list中的for element in list不起作用,因為項目不完全相同。

你能幫我找到解決我問題的辦法嗎?

謝謝!

刪除重復項的最佳方法是將它們添加到集合中。 將最后一個元素添加到set中以跟蹤所有唯一值。 當您要添加的值已經存在於 set unique ,如果不存在,則不執行任何操作,將值添加到 set unique並將 lst 附加到結果列表中,這是new

嘗試這個。

new=[]
unique=set()
for lst in RawData:
     if lst[-1] not in unique:
         unique.add(lst[-1])
         new.append(lst)

print(new)
#[['a', 'b', 'x', '15/30'],
 ['d', 'e', 'f', 'g', 'h', '20/30'],
 ['w', 'x', 'y', 'z', '10/10'],
 ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '20/60']]

您可以為唯一數據設置一個新數組並跟蹤您目前看到的項目。 然后,當您遍歷數據時,如果您之前沒有看到該列表中的最后一個元素,則將其附加到唯一數據並將其添加到看到的列表中。

RawData = [['a', 'b', 'x', '15/30'], ['d', 'e', 'f', 'g', 'h', '20/30'], ['w', 'x', 'y', 'z', '10/10'],
           ['a', 'x', 'c', '15/30'], ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '20/60'], ['x', 'b', 'c', '15/30']]
seen = []
UniqueData = []
for data in RawData:
    if data[-1] not in seen:
        UniqueData.append(data)
        seen.append(data[-1])

print(UniqueData)

輸出

[['a', 'b', 'x', '15/30'], ['d', 'e', 'f', 'g', 'h', '20/30'], ['w', 'x', 'y', 'z', '10/10'], ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '20/60']]
    RawData = [['a','b','x','15/30'],['d','e','f','g','h','20/30'],['w','x','y','z','10/10'],['a','x','c','15/30'],['i','j','k','l','m','n','o','p','20/60'],['x','b','c','15/30']]

seen = []
seen_indices = []

for _,i in enumerate(RawData):
  # _ -> index
  # i -> individual lists
  if i[-1] not in seen:
   seen.append(i[-1])
  else:
   seen_indices.append(_)

for index in sorted(seen_indices, reverse=True):
    del RawData[index]

print (RawData)

使用集合過濾掉已經看到其鍵的條目是最有效的方法。

這是一個使用帶有內部副作用的列表理解的單行示例:

UniqueData = [rd for seen in [set()] for rd in RawData if not(rd[-1] in seen or seen.add(rd[-1])) ]

暫無
暫無

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

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