我究竟做错了什么? Python阅读与区分

时间:2014-12-03 07:41:48

标签: python

编写一个程序,该程序从名为“distances.txt”的输入文件中读取,其格式如下:

John Smith 5 mi  
Mary Jones 8 km  
Jack Washington 3.8 mi  
Jill Adams 9.1 km 

您的程序应该输出一个名为“winner.txt”的文件,该文件是距离最远的人的全名。

到目前为止我有什么

def read(fileName):
    list2 =[]  
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append(words[2])
    maximum = max(list2)
    infile.close()
return

def rinter(fileName, maximum):
    infile = open(fileName, "r")
    for line in infile:
        if maximum in line:
            print(line)

    fileName = read("distances.txt")
    newcode = rinter(fileName,maximum)

    print(fileName)

4 个答案:

答案 0 :(得分:3)

请注意,函数内部的变量具有局部范围,您需要返回maximum函数中的read,然后将其作为rinter函数的参数:

def read(fileName):
    list2 =[]  
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append(words[2])
    maximum = max(list2)
    infile.close()
    return maximum


def rinter(fileName, maximum):
    infile = open(fileName, "r")
    for line in infile:
        if maximum in line:
             print(line)

maximum = read("distances.txt")
newcode = rinter("winner.txt",maximum)

但是这段代码只是添加到winner文件的距离,如果你需要用另一种算法添加你需要的全名,你需要保存一个分割行列表,但是从第一行切换到索引2然后找到最大使用max函数,其lambda函数为key,根据第2个索引找到最大值!然后将其写入您的文件,使用join函数加入索引:

def read(fileName):
    list2 =[]  
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append(words[:2])
    maximum = max(list2,key=lambda x:x[2])
    infile.close()
    return maximum


def rinter(fileName, maximum):
    infile = open(fileName, "r")
    infile.write(' '.join(maximum))
    print('winner is :'+' '.join(maximum))

maximum = read("distances.txt")
newcode = rinter("winner.txt",maximum)

如果您不想使用lambda(正如您在评论中所说),您可以使用列表理解: 所以替换以下行:

maximum = max(list2,key=lambda x:x[2])

with:

maximum = [l for l in list2 if l[2]==max(zip(*list2)[2])][0]

zip(*list2)为您提供list2列的列表,因此zip(*list2)[2]是距离列表,然后max(zip(*list2)[2])是您在选择最大值的条件下使用它的最大距离清单!而最后一个[0]是因为上面代码的结果是一个嵌套列表,其中一个索引[[]]需要内部列表!但我几乎不建议将max函数与lambda一起使用,它具有更高的性能,而且更强 pythonic

答案 1 :(得分:1)

对您的代码进行了一些更改:

list1 = []       # contain names
list2 = []       # contain distance
def read(fileName):
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        list1.append(" ".join(words[0:2]))
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            list2.append(float(words[2]))
       else:
           list2.append(float(words[2]))

    infile.close()
read("distances.txt")
maximum = max(list2)
winner = list1[list2.index(maximum)]
print(winner,maximum,"km")
f = open('winner.txt','w')
f.write(winner+" "+ str(mamimum)+" km")
f.close()

答案 2 :(得分:0)

您可能需要将字符串转换为double:

words[2] = words[2] / 0.62137

您必须返回最大值或将其声明为全局变量。

答案 3 :(得分:0)

我修复了你的阅读功能。现在它返回人名及其距离:

def read(fileName):
    list2 =[]
    infile = open(fileName, "r")
    for line in infile:
        words = line.split()
        #print(words)
        words[2] = float(words[2])
        if words[3] == "mi":
            words[2] = words[2] / 0.62137
            words[3] = "km"
            words[2] = float("{0:.1f}".format(words[2]))
        else:
            pass
        list2.append((' '.join(words[0:2]), words[2]))
    maximum = max(list2, key=lambda v: v[1])
    #print(list2, maximum)
    infile.close()
    return maximum

person_name, distance = read("data.csv")
print(person_name, distance)
#Jill Adams 9.1

不确定rinter应该做什么功能。

要将结果保存在输出文件中,您可以:

with open("winner.txt", 'w') as f:
    f.write(person_name + ' ' + str(distance))