首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的Python数字比较令人头疼

简单的Python数字比较令人头疼
EN

Stack Overflow用户
提问于 2012-12-26 09:27:10
回答 2查看 979关注 0票数 1

为了保持问题清晰,问题被注释在代码中:)

代码语言:javascript
复制
theOpenFile = open('text.txt', 'r')
highest = 0
for myCurrentString in theOpenFile.readlines():

                                          ## Simple string manipulation
    stringArray = myCurrentString.split() ## to get value, this seems to
    series = stringArray[0].split('.')[0] ## work perfectly when I
                                          ## "print series" at the end

    if series > highest:                  ## This doesn't work properly,
        highest = series                  ## although no syntantic or
        print "Highest = " + series       ## runtimes errors, just wrong output

    print series
theOpenFile.close()

输出

代码语言:javascript
复制
Highest = 8
8
Highest = 6
6
Highest = 6
6
Highest = 8
8
Highest = 8
8
Highest = 7
7
Highest = 4
4
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-26 09:31:04

您比较的是字符串,而不是数字,所以事情可能会变得有点奇怪。将您的变量转换为floatint,它应该可以工作

代码语言:javascript
复制
with open('text.txt', 'r') as theOpenFile:
    highest = 0
    for myCurrentString in theOpenFile:
        stringArray = myCurrentString.split()

        try:
            series = float(stringArray[0].split('.')[0])
        except ValueError:
            # The input wasn't a number, so we just skip it and go on
            # to the next one
            continue

        if series > highest:
            highest = series
            print "Highest = " + series

        print series

一种更简洁的方法是这样:

代码语言:javascript
复制
with open('text.txt', 'r') as handle:
    numbers = []

    for line in handle:
        field = line.split()[0]

        try:
            numbers.append(float(field))  # Or `int()`
        except ValueError:
            print field, "isn't a number"
            continue

    highest = max(numbers)
票数 2
EN

Stack Overflow用户

发布于 2012-12-26 12:32:28

假设文件中每个非空行的空格前都有一个点:

代码语言:javascript
复制
with open('text.txt') as file:
  highest = max(int(line.partition('.')[0]) for line in file if line.strip())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14035176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档