[英]How can I get the unique nested lists of a python list?
我的問題與嵌套在主列表中的列表的唯一性有關。 具體來說,我有以下結構,它是一個包含列表的lists
:
lst = [ [
[14], ['walk'], [69], ['walk'], [7]
],
[
[14], ['walk'], [69], ['walk'], [7]
],
[
[30], [948], [75], [947], [10]
],
[
[14]
]
]
為了獲得列表的獨特元素,我嘗試了 το 實現以下內容:
unique_data = [list(x) for x in set(tuple(x) for x in lst)]
但我收到以下錯誤:
TypeError: unhashable type: 'list'
。
預期的 output 如下:
[[[14], ['walk'], [69], ['walk'], [7]],
[[30], [948], [75], [947], [10]],
[[14]]]
有什么建議么?
嘗試:
lst = [
[[14], ["walk"], [69], ["walk"], [7]],
[[14], ["walk"], [69], ["walk"], [7]],
[[30], [948], [75], [947], [10]],
[[14]],
]
out, seen = [], set()
for subl in lst:
t = tuple(tuple(i) for i in subl)
if t not in seen:
seen.add(t)
out.append(subl)
print(out)
印刷:
[
[[14], ["walk"], [69], ["walk"], [7]],
[[30], [948], [75], [947], [10]],
[[14]],
]
如果你創建一個字典,並將值保存為鍵,那么如果順序很重要,你可以解決這個問題
lst = [[[14], ['walk'], [69], ['walk'], [7]], [[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]
unique = {}
for sublist in lst:
key = ''
for sub_sublist in sublist:
for value in sub_sublist:
key += '_' + str(value)
unique[key] = sublist
print(unique)
# output -> {'_14_walk_69_walk_7': [[14], ['walk'], [69], ['walk'], [7]], '_30_948_75_947_10': [[30], [948], [75], [947], [10]], '_14': [[14]]}
result = list(unique.values())
print(result)
# output. -> [[[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]
為了使用set()
,您需要將所有列表(和子列表)轉換為元組。
試試這個代碼:
unique = tuple([tuple([tuple(x) for x in y]) for y in lst])
unique = set(unique)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.