使用n + = 1和n = n + 1之间的区别

时间:2015-12-16 20:17:04

标签: python operators

到目前为止,我认为使用+ =运算符与使用诸如n = n + 1之类的东西相同。 在下面的代码中,当使用+ =表达式替换word_count [word] = word_count [word] + 1时,返回不同的结果。 有什么区别?

def word_count_dict(filename):
    word_count = {}
    opened_file = open(filename, 'r')
    for lines in opened_file:
        words = lines.split()
    for word in words:
        word = word.lower()
        if not word in word_count:
            word_count[word] = 1
        else:
            word_count[word] = word_count[word] + 1

    opened_file.close()
    return word_count

1 个答案:

答案 0 :(得分:2)

我测试过:

    word_count[word] = word_count[word] + 1

    word_count[word] += 1

并发现两个返回结果都是一样的。您是否上传了完整的代码,因为我无法复制您的问题,也许您忘记了一些更改输出的代码?

此外,您应该使用"而不是open()和close();声明因为它使用起来更安全。例如:

def word_count_dict(filename):
     word_count = dict()
     with open(filename, 'r') as file:
         for lines in file:
             words = lines.split()
         for word in words:
             word = word.lower()
             if not word in word_count:
                 word_count[word] = 1
             else:
                 word_count[word] += 1
     return word_count

修改

可以使用collections()中的defaultdict来重构代码

from collections import defaultdict

def word_count_dict(filename):
     word_count = defaultdict(int)
     with open(filename, 'r') as file:
         for lines in file:
             words = lines.split()
         for word in words:
             word_count[word.lower()] += 1
     return word_count