Skip to main content
 首页 » 编程设计

python之迭代嵌套列表并计算特定值

2025年05月04日20jillzhang

我有这个嵌套列表:

d = ['good morning', 'hello', 'chair', 'python', ['music', 'flowers',  
    'facebook', 'instagram', 'snapchat', ['On my Own', 'monster', 'Words  
     dont come so easily', 'lead me right']], 'Stressed Out', 'Pauver  
     Coeur', 'Reach for Tomorrow', 'mariners song', 'Wonder sleeps here'] 

我需要遍历列表,如果字符“m”在字符串中,则应将其添加到名为 m_list 的新列表中。

到目前为止我尝试的是以下内容:

m_list = [] 
for el in d: 
    print(" Level1: {}".format(el)) 
    if type(el) is str: 
        if 'm' in el: 
            m_list.append(el) 
    for el2 in el: 
        print(" Level2: {}".format(el2)) 
        if type(el2) is str: 
            if 'm' in el2: 
                m_list.append(el2) 
        for word in el2: 
            print(" Level3: {}".format(word)) 
            if type(word) is str: 
                if 'm' in word: 
                   m_list.append(word) 

我知道我没有正确设置代码,因为内部循环会重复计算某些元素。 作为示例:

print(m_list) 
 
['good morning', 'm', 'm', 'music', 'm', 'instagram', 'm', 'On my Own',  
'monster', 'Words dont come so easily', 'lead me right', 'Reach for  
Tomorrow', 'm', 'm', 'mariners song', 'm', 'm'] 

我用这个低效的代码解决了这个问题:

s = set(m_list) 
m_list = list(s) 
m_list.remove('m') 
print(m_list)  
['monster', 'mariners song', 'Words dont come so easily', 'Reach for  
Tomorrow', 'On my Own', 'lead me right', 'music', 'good morning',  
'instagram'] 

我的问题是如何更改 for 循环以便正确计算字符 'm' 并分配给 m_list?

附言我不是 Python 的熟练用户。我想提高我的技能。你愿意建议我更聪明的方法吗?

请您参考如下方法:

您可以创建一个通用的自定义函数,如果您在其中有列表,它会调用自身,或者如果它包含 'm' 则将值附加到新列表:

d = ['good morning', 'hello', 'chair', 'python', ['music', 'flowers',  
    'facebook', 'instagram', 'snapchat', ['On my Own', 'monster', 'Words  dont come so easily', 'lead me right']], 'Stressed Out', 'Pauver Coeur', 'Reach for Tomorrow', 'mariners song', 'Wonder sleeps here'] 
 
def find_all_values(d, m, m_list=[]): 
    for x in d: 
        if isinstance(x, list): 
            find_all_values(x, m, m_list) 
        elif m in x: 
            m_list.append(x)  
    return m_list 
 
 
m_list = find_all_values(d, 'm') 
# ['good morning', 'music', 'instagram', 'On my Own', 'monster', 'Words  dont come so easily', 'lead me right', 'Reach for Tomorrow', 'mariners song'] 
 
m_list_count = len(m_list) 
# 9 

现在您有了一个通用的自定义函数,您可以使用它来创建包含包含任何字母 的值的列表并获取它的计数。