某些值不会从循环中添加到我的字典中

时间:2017-11-12 01:56:20

标签: python dictionary

我有这段代码

def query(q, L):
    result = []
    mDict = {}
    key = 0
    for x, i in enumerate(L):
        for y in i:
            if q == y:
                key += 1

        if q in i:
            result.append(x)
            mDict[key]=x

        key = 0

    print (mDict)
    print (result)
q = "h"
l = ["phone", "power", "high", "phones"]
query(q, l)

我期待我的打印输出

{1: 0, 2: 2, 1: 3}

[0, 2, 3]

但我得到了

{1: 3, 2: 2}

[0, 2, 3]

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

您不需要复杂的函数来计算Python中的字符数,您可以使用str.count()

要整理计数,您可以使用collections.Counter

>>> from collections import Counter
>>> q = "h"
>>> l = ["phone", "power", "high", "phones"]
>>> Counter(word.count(q) for word in l)
Counter({1: 2, 0: 1, 2: 1})

答案 1 :(得分:0)

此代码有效

q = "h"
L = ["phone", "power", "high", "phones"]

mDict = {}
values = 0
for x, i in enumerate(L):
    for y in i:
        if q == y:
            values += 1

    if q in i:
        mDict[x]=values

    values = 0

sorted_dict = sorted(mDict, key=mDict.get, reverse=True)

print (sorted_dict)

输出

[2, 0, 3]