Skip to main content
 首页 » 编程设计

python之从嵌套列表和元组列表中获取所有唯一字符串

2025年05月04日24java哥

有没有一种快速获取唯一元素的方法,尤其是来自嵌套列表和元组的列表或元组中的字符串。应删除像“min”和“max”这样的字符串。列表和元组可以以任何可能的方式嵌套。唯一始终相同的元素是位于核心的元组,例如 ('a',0,49),其中包含字符串。

像那些列表或元组:

lst1=[[(('a',0,49),('b',0,70)),(('c',0,49))], 
     [(('c',0,49),('e',0,70)),(('a',0,'max'),('b',0,100))]] 
 
tuple1=([(('a',0,49),('b',0,70)),(('c',0,49))], 
     [(('c',0,49),('e',0,70)),(('a',0,'max'),('b',0,100))])  

想要的输出:

uniquestrings = ['a','b','c','e'] 

到目前为止我尝试了什么:

flat_list = list(sum([item for sublist in x for item in sublist],())) 

但这并没有到达嵌套对象的“核心”

请您参考如下方法:

这将获取给定可迭代对象内的任何字符串,无论可迭代对象内的位置如何:

def isIterable(obj): 
    # cudos: https://stackoverflow.com/a/1952481/7505395 
    try: 
        _ = iter(obj) 
        return True 
    except: 
        return False 
 
# shortcut 
isString = lambda x: isinstance(x,str) 
 
def chainme(iterab): 
    # strings are iterable too, so skip those from chaining 
    if isIterable(iterab) and not isString(iterab): 
        for a in iterab: 
            yield from chainme(a) 
    else:  
        yield iterab 
 
lst1=[[(('a',0,49),('b',0,70)),(('c',0,49))], 
     [(('c',0,49),('e',0,70)),(('a',0,'max'),('b',0,100))]] 
 
tuple1=([(('a',0,49),('b',0,70)),(('c',0,49))], 
     [(('c',0,49),('e',0,70)),(('a',0,'max'),('b',0,100))])  
 
 
for k in [lst1,tuple1]: 
    # use only strings 
    l = [x for x in chainme(k) if isString(x)] 
    print(l) 
    print(sorted(set(l))) 
    print() 

输出:

['a', 'b', 'c', 'c', 'e', 'a', 'max', 'b'] # list 
['a', 'b', 'c', 'e', 'max']                # sorted set of list 
 
['a', 'b', 'c', 'c', 'e', 'a', 'max', 'b'] 
['a', 'b', 'c', 'e', 'max']