【问题标题】:Why is my attempt to iterate through a list of lists and update dictionary values resulting in unchanged dictionary?为什么我尝试遍历列表列表并更新字典值导致字典未更改?
【发布时间】:2021-04-28 16:21:02
【问题描述】:

我想遍历列表列表,如果列表中的实例与字典中的键匹配,则将 1 添加到该字典键值。但是,当我执行我的代码时,它会返回字典而不更改值。感谢您的时间和帮助。我搜索了一个类似的问题,但没有找到解决这个问题的问题。如果我错过了,我深表歉意。

我有一份飓风及其影响地区的清单。我有一个字典,其中包含唯一受影响区域的键、值对以及受影响的次数(设置为零)。我想遍历 hurricane 实例列表,每次通过字典中的某个位置时,将唯一区域的值增加 1。目前,我正在运行返回的字典的代码保持不变。

我已经包含了我正在使用的材料的较小示例: (test_list 是受飓风影响的地区列表,从而产生列表列表)

test_list = [['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], ['The Bahamas', 'Northeastern United States'], ['Lesser Antilles', 'Jamaica', 'Cayman Islands', 'Cuba', 'The Bahamas', 'Bermuda']]

test_dict = {
'Central America': 0, 'Mexico': 0, 'Cuba': 0, 'Florida', 0, 'The Bahamas': 0, 'Lesser Antilles': 0, 'United States East Coast', 'Atlantic Canada': 0, 'Northeastern United States': 0, 'Jamaica': 0, 'Cayman Islands': 0, 'Bermuda': 0}

目标

如果我表演了:

area_counted = area_counter(test_list, test_dict)

我早就料到了:

area_counted = {
'Central America': 1, 'Mexico': 1, 'Cuba': 2, 'Florida', 1, 'The Bahamas': 4, 'Lesser Antilles': 2, 'United States East Coast': 1, 'Atlantic Canada': 1, 'Northeastern United States': 1, 'Jamaica': 1, 'Cayman Islands': 1, 'Bermuda': 1}

但是,这不是我的结果。

代码

def area_count(input_dict, input_list):
  new_dict = {}
  new_dict.update(input_dict)
  for i in list:
      for j in i:
        if j == new_dict[j]:
          new_dict[j] += 1
        else:
          pass
  return new_dict

area_counted = area_count(test_dict, test_list)
print(area_counted)

输出以下内容:

area_counted = {
'Central America': 0, 'Mexico': 0, 'Cuba': 0, 'Florida', 0, 'The Bahamas': 0, 'Lesser Antilles': 0, 'United States East Coast', 'Atlantic Canada': 0, 'Northeastern United States': 0, 'Jamaica': 0, 'Cayman Islands': 0, 'Bermuda': 0}

edit-1:将 area_count 参数编辑为 input_list 而不是 list,更正了 area_counted 的参数输入顺序以匹配 area_count 函数。

【问题讨论】:

  • if j == new_dict[j]: 永远不会为真,因为new_dict[j] 将是一个int,如0,而j 将是一个类似'Central America' 的字符串
  • 这肯定不是你尝试过的。您的代码根本不运行。 1) SyntaxError: invalid syntax,因为您的字典定义没有创建字典。 2)您以错误的顺序传递参数
  • @ThomasWeller 您能否详细说明字典创建问题?我有new_dict = {},更新new_dict,然后在函数末尾返回new_dict。我错过了什么?感谢您指出我的参数错误,我显然应该在发布之前发现它。

标签: python list dictionary iteration


【解决方案1】:

new_dict[j]最初总是等于0(因为在test_dict中所有的值都是0)

您正在将其与字符串进行比较

if "Central America" == 0:
    set_to_1()

希望你能看到它是如何永远不会设置为 1 的

我想你想要的是

if j in new_dict:
    new_dict[j] = 1

除此之外,您真的不应该将变量命名为 list,因为它是一个内置实体,您最终会被隐藏

【讨论】:

  • 乔丹,感谢您的反馈。它帮助我看到我的 if 语句正在将字符串与值进行比较。您的建议,if j in new_dict: 为我解决了这个问题。
猜你喜欢
  • 2018-04-12
  • 2012-03-09
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多