【问题标题】:Why does my dictionary creation for loop stop halfway Python为什么我的字典创建循环中途停止Python
【发布时间】:2021-05-24 17:21:52
【问题描述】:

我正在尝试创建一个字典,它包含整个字母表并将每个字母用作键,然后它的值使用该字母两次。我写了以下代码:

import string
alphabet = list(string.ascii_lowercase)

main_dict = {}
for x in alphabet:
      key = alphabet.pop()
      value = key + key
      new_dict = dict.fromkeys(key, value)
      main_dict.update(new_dict) 
      print(main_dict)

这似乎有效,直到我到达字母 N 然后它停止迭代。

这是它的输出:

{'z': 'zz', 'y': 'yy', 'x': 'xx', 'w': 'ww', 'v': 'vv', 'u': 'uu', 't': 'tt', 's': 'ss', 'r': 'rr', 'q': 'qq', 'p': 'pp', 'o': 'oo', 'n': 'nn'}

【问题讨论】:

  • 欢迎来到 StackOverflow!如果您是 Python 新手,您可能也很高兴知道 value = key * 2 也可以。

标签: python dictionary for-loop


【解决方案1】:

问题

您使用x 向前迭代,然后使用key = alphabet.pop() 从末尾删除,所以当您到达中途时,您已经删除了第二半,所以没有没有可以迭代

打印x, key, alphabet

a z ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']
b y ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']
c x ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']
d w ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']

修复和改进

  • 仅使用x 读取字母表
  • 不要创建中间new_dict:在main_dict中添加映射
  • 你可以迭代str string.ascii_lowercase,不需要list
import string

main_dict = {}
for key in string.ascii_lowercase:
    main_dict[key] = key * 2

dict-comprehension 版本是

main_dict = {key: key * 2 for key in string.ascii_lowercase}

【讨论】:

  • 也可以这样:main_dict.update({key: key+key})
  • 谢谢!只是好奇使用 .pop 时您提到在进行到一半之后就什么都没有了,您知道这是为什么吗?对不起,如果这是一个愚蠢的问题..
  • @Douet 方法pop 删除并返回最后一项
【解决方案2】:

这是因为您从字母表中弹出元素。这样做:

import string

alphabet = list(string.ascii_lowercase)
main_dict = {}
for x in alphabet:
     main_dict[x] = x+x
     
print(main_dict)

【讨论】:

    【解决方案3】:

    您正在迭代时修改列表(使用alphabet.pop(),这会导致不良行为 - 此处停止在字母N)。为了得到想要的结果,你可以使用 dict-comprehension:

    import string
    
    alphabet = string.ascii_lowercase
    
    main_dict = {ch: ch * 2 for ch in alphabet}
    print(main_dict)
    

    打印:

    {'a': 'aa', 'b': 'bb', 'c': 'cc', 'd': 'dd', 'e': 'ee', 'f': 'ff', 'g': 'gg', 'h': 'hh', 'i': 'ii', 'j': 'jj', 'k': 'kk', 'l': 'll', 'm': 'mm', 'n': 'nn', 'o': 'oo', 'p': 'pp', 'q': 'qq', 'r': 'rr', 's': 'ss', 't': 'tt', 'u': 'uu', 'v': 'vv', 'w': 'ww', 'x': 'xx', 'y': 'yy', 'z': 'zz'}
    

    【讨论】:

    • 这个问题似乎更多地询问为什么代码不起作用。虽然我喜欢你解决问题的方法,但我认为它不能回答 OP 的问题
    • @MuhdMairaj 已添加。
    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2019-03-03
    相关资源
    最近更新 更多