我有一本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
它没有给我想要的。你知道吗
我在你的例子中看到两个问题。你知道吗
首先是分数没有增加。您应该在外循环中初始化一个计数器,并在迭代键中的项时递增它。你知道吗
第二个问题是,在存储分数时,需要访问正在评分的特定键。“作为”原始密钥()”返回所有键的列表,在存储值时使用它没有意义。 相反,您的外循环应该迭代键和值,这样您就可以知道当前使用的键。你知道吗
总而言之,下面是一个工作示例:
玩得开心!你知道吗
您试图使用整个键列表作为字典的索引。另外,你把这个赋值放在两个循环中。您希望在每次迭代中都做些什么?你知道吗
首先,外部循环必须遍历字典元素列表,而不仅仅是值。你需要这样的东西:
接下来,您需要维护单个字符串的总分数。你应该查一下这个。。。但基本思想是
。。。最后,在这个循环之后。。。你知道吗
这会让你向前迈进。你知道吗
您需要遍历字典的所有键、值对,并维护字典值的每个元素(在您的示例中是一个列表)的运行总分。你知道吗
您可以按如下方式修改代码以获得所需的输出。你知道吗
它输出:
因此,循环
for key, value in raw.items():
为字典的每个键、值对运行,它们是'id1': ['KKKK', 'MMMMMMMMMMMMMMM']
和'id2': ['KKKKM', 'KKKKKK']
。你知道吗然后,嵌套循环
for item in value:
为两个字典键的值运行两次,它们是['KKKK', 'MMMMMMMMMMMMMMM']
和['KKKKM', 'KKKKKK']
。你知道吗相关问题 更多 >
编程相关推荐