如何理解这个python代码?
这段代码来自学习python一书,用于对文本文件中由逗号分隔的列求和。我真的不懂第7、8和9行。 谢谢你的帮助。代码如下:如何理解这个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
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
道歉,但在我写这本书的时候它没有这样说。道歉,但在我写这本书的时候它没有这样说。