繁体   English   中英

Python:For 循环在第一次迭代后停止向字典添加项目和值

[英]Python: For loop stops adding items and values to a dictionary after first iteration

我正在玩和学习 python,无论如何我想将单词分成两半并计算单词中每个字母的出现并将分数插入字典 output 应该是这样的:

单词:aaazzbbb dict1:单词的前半部分

{'a': 3,'z': 1}

问题是添加停止 dict2: 后半部分

{'b': 3,'z': 1}

因为在使用 for 循环的第一次迭代后似乎停止向字典添加项目,这很奇怪。

在我的 function 和它给出的下面

def pal2(word):
    wordLength = len(word)
    word1 = ""
    word2 = ""
    midstr = ""
    dict1 = []
    dict2 = []
    if (wordLength % 2 == 0 ):
        for i in range(int((len(word)/2)-1),-1,-1):
            word1 += word[i]

            if (word[i] not in dict1):
                dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}
        for j in range(int((len(word)/2)),len(word),+1):
            word2 += word[j]

            if (word[j] not in dict2):
                dict2 = {word[j]:word.count(word[j],int((len(word) / 2) - 1), len(word))}

这就是它给出的

{'a': 3}, {'b': 3}

如您所见,仅插入了第一个字母

您的代码有很多问题,我已经修复了其中一些问题以使其正常工作:

  1. 您像lists一样初始化dict1dict2 ,而不是dicts
  2. 在每次for循环迭代中,您都会完全覆盖您的 dict,因此结果中只有一个键。
dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}
  1. 您在count function 中使用了不正确的索引。 你必须使用
word.count(word[i], 0, int((len(word) / 2)))

代替

word.count(word[i],0,int((len(word)/2)-1))

word.count(word[j], int((len(word) / 2)), len(word))

代替

word.count(word[j],int((len(word) / 2) - 1), len(word))
  1. function 中的变量应该是小写的,所以我用wordLength替换了word_length 您必须遵守这些标准以提高代码的可读性。
  2. 修复了一些其他代码样式问题。
def pal2(word):
    word_length = len(word)
    word1 = ""
    word2 = ""
    dict1 = {}
    dict2 = {}
    if word_length % 2 == 0:
        for i in range(int((len(word) / 2) - 1), -1, -1):
            word1 += word[i]
            if word[i] not in dict1:
                dict1[word[i]] = word.count(word[i], 0, int((len(word) / 2)))
        for j in range(int((len(word) / 2)), len(word), 1):
            word2 += word[j]
            if word[j] not in dict2:
                dict2[word[j]] = word.count(word[j], int((len(word) / 2)), len(word))
    print(dict1)
    print(dict2)


pal2("aaazzbbb")

Output:

{'z': 1, 'a': 3}
{'z': 1, 'b': 3}

您需要更新初始字典,而不是每次都创建字典。

为了解释,首先你必须创建一个空字典:

dict1 = {}

然后,我们替换此代码,您将在其中创建一个全新的字典:

dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}

通过这个(更新原始字典,以包含现有元素):

dict1.update({word[i]:word.count(word[i],0,int((len(word)/2)))})

检查更新方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM