问题描述
虽然我对 bash 有很多经验,但我对 python 还是很陌生.我有一个由单列数字组成的文件,我想在列表中找到最大的数字.我尝试使用以下代码:
I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:
i = 0
with open('jan14.nSets.txt','r') as data:
for num in data:
if num > i:
i = num
print(i)
其中 jan14.nSets.txt 如下:
where jan14.nSets.txt is the following:
12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198
我收到的不是 270,而是 9 作为输出,我不明白为什么会这样.我知道有内置插件,但我想知道为什么这不能帮助我理解语言.我正在使用python2.7
Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7
推荐答案
num
是一个字符串,而不是一个数字.首先使用 int()
将其转换为整数一个>:
num
is a string, not a number. Turn it into an integer first using int()
:
num = int(num)
您正在比较文本,所以它是按按字典顺序排列的,'9' >'80'
因为 ASCII 字符 '9'
的代码点比 '8'
高:
You are comparing text, so it is ordered lexicographically, '9' > '80'
because the ASCII character '9'
has a higher codepoint than '8'
:
>>> '9' > '80'
True
在 '9'
行之后,所有其他行的初始数字要么小于 '9'
,要么该行相等.
After the '9'
line, all other lines either have an initial digit that is smaller than '9'
, or the line is equal.
您可以使用 max()
函数 代替,前提是您首先使用 map()
将所有行转换为整数:
You could use the max()
function instead, provided you first use map()
to turn all lines into integers:
with open('jan14.nSets.txt','r') as data:
i = max(map(int, data))
或使用 生成器表达式(在 Python 2 中,比 map()
) 更节省内存:
or use a generator expression (in Python 2, more memory efficient than map()
):
with open('jan14.nSets.txt','r') as data:
i = max(int(num) for num in data)
两者都从 data
中提取所有行,将这些行映射为整数,并从中确定最大值.
Both pull in all lines from data
, map the lines to integers, and determine the maximum value from those.
这篇关于为什么我在这样的文件中找不到最大数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!