嵌套列表的for循环计数

问题描述 投票:0回答:1

嘿,我正在努力弄清楚如何在 python 中计数,我需要它计算名称,然后必须将它们添加到字典中,或者如果有其他替代方法,所以从列表中它需要匹配第二个列表中的名称

list_1 = ['red', 'blue', 'green']
nested_list_1= [['red','hair','peaches'],['green', 'hair', 'roses'],['green', 'same', 'roses'],['red', 'same', 'roses'],['green', 'same', 'roses']]
dic = {}
count = 0
for x in list_1:

    # print(x)
    # count = 
    for y in nested_list_1:
   
        if x in y[0]:
           
            count +=1
            dic[y[0]] = count

我尝试添加计数器循环,它对名称进行计数,但仅对第一个名称进行计数,然后对列表中的第二个名称进行计数,但之后计数不正确

python nested counter
1个回答
0
投票

仅用一个计数器无法做到这一点。我想对于每个不同的单词,您需要单独的计数,因此请使用

dic
中的条目查看之前的计数,然后为其添加 1。

其次,对于字典中的键,您不想使用

y[0]
,而是使用
x
,因为that是您正在计算的单词:

for x in list_1:
    for y in nested_list_1:
        if x in y[0]:
            if x not in dic:
                dic[x] = 1
            else:
                dic[x] +=1
© www.soinside.com 2019 - 2024. All rights reserved.