[英]Finding unique elements in nested list
如果我有一個列表mylist = [“ [amn,b,c]”,“ ['a,d,e']”,“ ['f,b,e']”]] ,並且我需要一個列表使用[amn,b,c,d,e,f]的所有唯一元素,我該如何實現?
我嘗試過創建一個函數,也嘗試過其他方法,但無濟於事。
功能:
mylist = ["[amn,b,c]", "[‘a,d,e’]", "[‘f,b,e’]"]
def print_list(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_list(each_item)
else:
print(each_item)
print_list(mylist)
輸出:
[amn,b,c]
[‘a,d,e’]
[‘f,b,e’]
其他方法:
mylist = ["[amn,b,c]", "[‘a, d,e’]", "[‘f,b,e’]"]
mylist = str(mylist)
mylist = str(mylist)
mylist = [str(x) for x in (mylist)]
mylist = set(mylist)
i = {' ', "'", ',', '[', ']','‘', '’'}
mylist.difference_update(i)
mylist = list(mylist)
mylist.sort()
mylist
輸出:
['a', 'b', 'c', 'd', 'e', 'f', 'm', 'n']
預期成績:
[amn,b,c,d,e,f]
實際結果:
具有的功能:
[amn,b,c]
[‘a,d,e’]
[‘f,b,e’]
用另一種方法:
['a', 'b', 'c', 'd', 'e', 'f', 'm', 'n']
您可以使用以下列表re.sub
方法,其中使用re.sub
來刪除不需要的字符,並且使用.split
並用,
拆分來獲取基礎列表。
最后,為了從嵌套列表中獲取唯一元素,可以使用itertools.chain
展平嵌套列表,並從結果生成一個set
以保留唯一值:
import re
from itertools import chain
set(chain(*[re.sub(r'[\[‘’\"\]]', '', i).split(',') for i in mylist]))
{'a', 'amn', 'b', 'c', 'd', 'e', 'f'}
哪里:
[re.sub(r'[\[‘’\"\]]', '', i).split(',') for i in mylist]
[['amn', 'b', 'c'], ['a', 'd', 'e'], ['f', 'b', 'e']]
我必須重新定義列表,因為在您有1個帶有字符串的列表之前。 如果這是錯誤的,請讓我知道,但是我很好奇您為什么要列出類似列表的字符串。
mylist = [['amn','b','c'], ['a','d','e'], ['f','b','e']]
unique_list = []
def find_all_unique(input, unique_list):
if type(input) is list:
return [find_all_unique(x, unique_list) for x in input if x is not None]
if type(input) is str:
if input not in unique_list:
unique_list.append(input)
find_all_unique(mylist, unique_list)
print(unique_list)
結果:
['amn', 'b', 'c', 'a', 'd', 'e', 'f']
[Finished in 0.081s]
或者,如果您需要將嵌套列表保留在引號內,則可以使用以下方法:
mylist = [['amn','b','c', "['r','t','x']"], ['a','d','e'], ['f','b','e']]
unique_list = []
def find_all_unique(input, unique_list):
if type(input) is list:
return [find_all_unique(x, unique_list) for x in input if x is not None]
if type(input) is str:
if input.startswith('['):
temp_list=[]
exec("temp_list.append(" + input + ')', {"temp_list":temp_list})
return [find_all_unique(x, unique_list) for x in temp_list if x is not None]
elif input not in unique_list:
unique_list.append(input)
find_all_unique(mylist, unique_list)
print(unique_list)
為了測試這一點,我添加了一個字符串列表"['r','t','x']"
,它應該捕獲r
, t
, x
作為唯一輸入
結果:
['amn', 'b', 'c', 'r', 't', 'x', 'a', 'd', 'e', 'f']
[Finished in 0.077s]
無論函數是列表列表還是字符串列表,都可以使用,因為該函數是遞歸的。
首先,我將嘗試用,
(逗號), '
(單引號), []
(使用模式匹配用空字符串打開封閉的方括號。然后使用set
刪除重復項,並使用list
重建list
,如下所示:
my_list = ["[amn,b,c]", "['a, d,e']", "['f,b,e']"]
result = sorted(list(set(([letter for word in my_list for letter in re.sub(',|\'|\[|]|\s+', '', word)]))))
print(result)
哪里
re.sub(',|\'|\[|]|\s+', '', word)])
將替換字符串中的特殊字符。 例如, ['a, d,e']
到ade
。
基於理解的解決方案在技術上等於
result = []
for word in my_list: # Break list of lists to lists
word = re.sub(',|\'|\[|]|\s+', '', word)
for letter in word: # Process each word in the sub list
result.append(letter)
print('results with duplicates: ', result) # List with possible duplicates
result = set(result) # Remove duplicates by converting to a set
result = list(result) # Convert set back to list without duplicates (order is not preserved)
print('results without duplicates: ', result)
result = sorted(result)
print('results in sorted order: ', result)
結果是
results with duplicates: ['a', 'm', 'n', 'b', 'c', 'a', 'd', 'e', 'f', 'b', 'e']
results without duplicates: ['e', 'a', 'd', 'm', 'f', 'c', 'n', 'b']
results in sorted order: ['a', 'b', 'c', 'd', 'e', 'f', 'm', 'n']
dd = []
mylist = ["[amn,b,c]", "[‘a,d,e’]", "[‘f,b,e’]"]
for i in mylist:
dd.extend([''.join(filter(str.isalnum, j)) for j in i.split(",")])
print (list(set(dd)))
#output ['f', 'a', 'b', 'amn', 'c', 'd', 'e']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.