python词典中的评分主题

2024-09-30 08:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本python词典,看起来像这样:

raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}

如您所见,这些值是列表中的值。我想用一个得分的数字来代替名单。我根据每个角色的长度给他们打分。如果长度是4到9,他们将得到1,从10到15将是2和16,更长的将得到3。然后我将每个id的所有分数相加,每个id有一个分数。下面是一个小示例:

score = {'id1': 3, 'id2': 2}

我试过这个代码:

score = {}
for val in raw.values():
    for i in val:
        if len(i) >=4 and len(i) <9:
            sc = 1
        elif len(i) >=10 and len(i) <15:
            sc = 2
        else:
            sc = 3
        score[raw.keys()] = sc

它没有给我想要的。你知道吗


Tags: andinidforrawlenval分数
3条回答

我在你的例子中看到两个问题。你知道吗

首先是分数没有增加。您应该在外循环中初始化一个计数器,并在迭代键中的项时递增它。你知道吗

for val in raw.values():
    score = 0
    for i in val:
        ...
        score += 1  # or 2 or 4

第二个问题是,在存储分数时,需要访问正在评分的特定键。“作为”原始密钥()”返回所有键的列表,在存储值时使用它没有意义。 相反,您的外循环应该迭代键和值,这样您就可以知道当前使用的键。你知道吗

for key, val in raw.items():
    ....

总而言之,下面是一个工作示例:

score = {}
for key, val in raw.items():  # iterating over both key and value (.items instead of .values)
    cur_score = 0  # initializing the current score counter
    for item in val:  # use readable names!
        item_len = len(item)  # calculated once for efficiency
        if 4 <= item_len < 9:  # the python way to check value in range
            cur_score += 1
        elif 10 <= item_len < 15:
            cur_score += 2
        else:
            cur_score += 3
        score[key] = cur_score

玩得开心!你知道吗

您试图使用整个键列表作为字典的索引。另外,你把这个赋值放在两个循环中。您希望在每次迭代中都做些什么?你知道吗

首先,外部循环必须遍历字典元素列表,而不仅仅是值。你需要这样的东西:

for key, val in raw.iteritems():

接下来,您需要维护单个字符串的总分数。你应该查一下这个。。。但基本思想是

    total = 0
    for item in my_list:  # you have to determine what my_list should be
        sc = # score for that item
        total += sc

。。。最后,在这个循环之后。。。你知道吗

    score[key] = total

这会让你向前迈进。你知道吗

您需要遍历字典的所有键、值对,并维护字典值的每个元素(在您的示例中是一个列表)的运行总分。你知道吗

您可以按如下方式修改代码以获得所需的输出。你知道吗

raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}

score = {}
# iterating through all the key, value pairs of the dictionary
for key, value in raw.items():
    sc = 0
    # iterating through all the elements of the current value
    for item in value:
        if len(item) >=4 and len(item) <=9:
            sc += 1
        elif len(item) >=10 and len(item) <=15:
            sc += 2
        else:
            sc += 3
    score[key] = sc

print(score)

它输出:

{'id1': 3, 'id2': 2}

因此,循环for key, value in raw.items():为字典的每个键、值对运行,它们是'id1': ['KKKK', 'MMMMMMMMMMMMMMM']'id2': ['KKKKM', 'KKKKKK']。你知道吗

然后,嵌套循环for item in value:为两个字典键的值运行两次,它们是['KKKK', 'MMMMMMMMMMMMMMM']['KKKKM', 'KKKKKK']。你知道吗

相关问题 更多 >

    热门问题