Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何理解这个python代码?_Python - Fatal编程技术网

如何理解这个python代码?

如何理解这个python代码?,python,Python,这段代码来自学习python一书,用于对文本文件中由逗号分隔的列求和。我真的不懂第7、8和9行。 谢谢你的帮助。代码如下: filename='data.txt' sums={} for line in open(filename): cols=line.split(',') nums=[int(col) for col in cols] for(ix, num) in enumerate(nums): sums[ix]=sums.get(ix, 0)+n

这段代码来自学习python一书,用于对文本文件中由逗号分隔的列求和。我真的不懂第7、8和9行。 谢谢你的帮助。代码如下:

filename='data.txt'
sums={}
for line in open(filename):
    cols=line.split(',')
    nums=[int(col) for col in cols]
    for(ix, num) in enumerate(nums):
        sums[ix]=sums.get(ix, 0)+num
for key in sorted(sums):
    print(key, '=', sums[key])

输入文件似乎包含以逗号分隔的整数行。这个程序打印出每列的总和

你把缩进弄混了,它改变了程序的意义,而且它一开始写得不是很好。这里有很多评论:

filename='data.txt'    # name of the text file

sums = {}              # dictionary of { column: sum }
                       #   not initialized, because you don't know how many columns there are

# for each line in the input file,
for line in open(filename):
    # split the line by commas, resulting in a list of strings
    cols = line.split(',')
    # convert each string to an integer, resulting in a list of integers
    nums = [int(col) for col in cols]

    # Enumerating a list numbers the items - ie,
    #   enumerate([7,8,9]) -> [(0,7), (1,8), (2,9)]
    # It's used here to figure out which column each value gets added to
    for ix, num in enumerate(nums):
        # sums.get(index, defaultvalue) is the same as sums[index] IF sums already has a value for index
        # if not, sums[index] throws an error but .get returns defaultvalue
        # So this gets a running sum for the column if it exists, else 0;
        # then we add the new value and store it back to sums.
        sums[ix] = sums.get(ix, 0) + num

# Go through the sums in ascending order by column -
#   this is necessary because dictionaries have no inherent ordering
for key in sorted(sums):                    
    # and for each, print the column# and sum
    print(key, '=', sums[key])
我会写得有点不同;差不多

from collections import Counter
sums = Counter()

with open('data.txt') as inf:
    for line in inf:
        values = [int(v) for v in line.split(',')]
        sums.update(enumerate(values))

for col,sum in sorted(sums.iteritems()):
    print("{}: {}".format(col, sum))

输入文件似乎包含以逗号分隔的整数行。这个程序打印出每列的总和

你把缩进弄混了,它改变了程序的意义,而且它一开始写得不是很好。这里有很多评论:

filename='data.txt'    # name of the text file

sums = {}              # dictionary of { column: sum }
                       #   not initialized, because you don't know how many columns there are

# for each line in the input file,
for line in open(filename):
    # split the line by commas, resulting in a list of strings
    cols = line.split(',')
    # convert each string to an integer, resulting in a list of integers
    nums = [int(col) for col in cols]

    # Enumerating a list numbers the items - ie,
    #   enumerate([7,8,9]) -> [(0,7), (1,8), (2,9)]
    # It's used here to figure out which column each value gets added to
    for ix, num in enumerate(nums):
        # sums.get(index, defaultvalue) is the same as sums[index] IF sums already has a value for index
        # if not, sums[index] throws an error but .get returns defaultvalue
        # So this gets a running sum for the column if it exists, else 0;
        # then we add the new value and store it back to sums.
        sums[ix] = sums.get(ix, 0) + num

# Go through the sums in ascending order by column -
#   this is necessary because dictionaries have no inherent ordering
for key in sorted(sums):                    
    # and for each, print the column# and sum
    print(key, '=', sums[key])
我会写得有点不同;差不多

from collections import Counter
sums = Counter()

with open('data.txt') as inf:
    for line in inf:
        values = [int(v) for v in line.split(',')]
        sums.update(enumerate(values))

for col,sum in sorted(sums.iteritems()):
    print("{}: {}".format(col, sum))

假设您理解第1-6行

第7行:

sums[ix]=sums.get(ix, 0)+num
sums.get(ix,0)
sums[ix]
相同,只是如果
ix不在sums
中,则返回
0
。因此,这就像是
sums[ix]+=num
,只是如果这是您第一次看到
ix
,它首先将值设置为
0

因此,应该很清楚,在这个循环结束时,
sums[ix]
将拥有列
ix
中所有值的总和

这是一种愚蠢的做法。正如mgilson指出的,您可以只使用
defaultdict
,因此不需要额外的逻辑。或者,更简单地说,您可以使用
列表
而不是
dict
,因为这(按顺序小数字索引)正是
列表
的作用

第8行:

for key in sorted(sums):
首先,您可以迭代任何
dict
,就像它是
列表或其他iterable一样,它的效果与迭代
sums.keys()
相同。因此,如果
sums
看起来像
{0:4,1:6,2:3}
,您将在
0,1,2
上迭代

除了
dict
s没有任何固有的顺序。您可以获得
0,1,2
,也可以获得
1,0,2
或任何其他订单

因此,
sorted(sums)
只返回按排序顺序排列的键的
列表的副本,保证您将按该顺序得到
0,1,2

同样,这是愚蠢的,因为如果你首先使用
列表
,你会把事情安排得井井有条

第9行:

print(key, '=', sums[key])
这一点应该是显而易见的。如果
0,1,2
上迭代,则将打印
0=4
1=6
2=3


换句话说,它打印出每一列的编号,以及该列中所有值的总和。

假设您理解第1-6行

第7行:

sums[ix]=sums.get(ix, 0)+num
sums.get(ix,0)
sums[ix]
相同,只是如果
ix不在sums
中,则返回
0
。因此,这就像是
sums[ix]+=num
,只是如果这是您第一次看到
ix
,它首先将值设置为
0

因此,应该很清楚,在这个循环结束时,
sums[ix]
将拥有列
ix
中所有值的总和

这是一种愚蠢的做法。正如mgilson指出的,您可以只使用
defaultdict
,因此不需要额外的逻辑。或者,更简单地说,您可以使用
列表
而不是
dict
,因为这(按顺序小数字索引)正是
列表
的作用

第8行:

for key in sorted(sums):
首先,您可以迭代任何
dict
,就像它是
列表或其他iterable一样,它的效果与迭代
sums.keys()
相同。因此,如果
sums
看起来像
{0:4,1:6,2:3}
,您将在
0,1,2
上迭代

除了
dict
s没有任何固有的顺序。您可以获得
0,1,2
,也可以获得
1,0,2
或任何其他订单

因此,
sorted(sums)
只返回按排序顺序排列的键的
列表的副本,保证您将按该顺序得到
0,1,2

同样,这是愚蠢的,因为如果你首先使用
列表
,你会把事情安排得井井有条

第9行:

print(key, '=', sums[key])
这一点应该是显而易见的。如果
0,1,2
上迭代,则将打印
0=4
1=6
2=3


换句话说,它将打印出每一列的编号,以及该列中所有值的总和。

缩进在Python中非常重要。为避免难以找到的bug,请始终使用空格;不要混合使用制表符和空格。这本书并不特别好,因为在enumerate(nums)中的
for(ix,num):
-你不需要
()
围绕
ix,num
缩进在Python中很重要。为避免难以找到的bug,请始终使用空格;不要混合制表符和空格。这本书不是特别好,因为在枚举(nums)中的
for(ix,num):
-你不需要
()
围绕
ix,num
道歉,但在我写这本书的时候它没有这样说。道歉,但在我写这本书的时候它没有这样说。