为什么这个变量是空序列?

时间:2015-01-26 09:35:40

标签: python variables

我正在使用的代码是在文本文件

中选择三个中最高的数字
R 3 5 7
F 2 9 6
I 6 3 5

当它运行时,它会将正确的信息发送到文本文件,但会出现

 max_in_line = max(nums)
 ValueError: max() arg is an empty sequence

我的代码是

with open (classno, 'r') as f, open("class11.txt", 'w') as fout:

      for line in f.readlines(): #does right swaps around
           if not line.strip(): continue
           parts = line.split()
           nums_str = line.split()[1:]
           nums = [int(n) for n in nums_str]
           max_in_line = max(nums)
           print (max_in_line)
           print (line)

           score = (max_in_line)#same problem
           name = (parts[0])
           fout.write(("\n") + str(score) + (" ") + (name))

      fout.close
      f.close#it does write them but comes up with the problem

1 个答案:

答案 0 :(得分:0)

尝试此代码,只需跳过列表中的空行或空元素:

with open ('classno.txt', 'r') as f, open("class11.txt", 'w') as fout:
  lines = [line.strip() for line in f]
  for line in lines:
    splitted = [i for i in line.split(' ') if i]
    nums = splitted[1:]
    max_nums = max(map(int, nums))
    name = splitted[0]
    fout.write('\n' + str(max_nums) + ' ' + name)

它对我有用,希望有所帮助。