【问题标题】:Python - Multiple 'split' ErrorPython - 多个“拆分”错误
【发布时间】:2018-09-07 00:59:23
【问题描述】:

我 4-5 天前在这里发帖,关于从文件中对一些数字进行排序的一个问题。 现在,与另一个问题相同,但是我想将数字从一个文件 (x) 排序到另一个文件 (y)。例如:在 x 我有:(5,6,3,11,7),我想把这个数字排序为 y (3,5,6,7,11)。但是我有一些错误,无法自行解决,我不明白,您能帮帮我吗?

from sys import argv
try:
    with open(argv[1],"r") as desti:
        cad = desti.readlines()
        k= list(cad)
        for n in range(len(cad)):
            k = n.split(',') 
            k = (int, cad)
            k = sorted(cad)
        with open("nums_ordenats.txt","w") as prl:
            prl.write(k)
except Exception as err:
    print(err, "Error")

其实报错信息是“'int' object has no attribute 'split'错误 ”。 我认为代码是正确的。此外,该程序告诉我其他错误,但我如何每次更改代码,它们也会改变。

坦克很多!

【问题讨论】:

  • n 是整数,而不是字符串。这就是您收到此错误的原因。
  • n 是一个整数。也许你的意思是cad[n].split(',')
  • 感谢大家(我从帖子中编辑了代码)。现在错误是:“列表索引必须是整数,而不是 str 错误”。真的,我无法理解这个错误,我已经尝试做这个程序超过 1 周了,我认为这很简单。
  • 您的文件是否有(5,6,3,11,7)(包括括号),还是只有5,6,3,11,7

标签: python python-3.x list sorting tuples


【解决方案1】:

您的代码存在太多问题,我无法解决。试试这个:

from sys import argv

with open(argv[1], "r") as infile:
    with open("nums_ordenats.txt", "w") as outfile:
        for line in infile:
            nums = [int(n) for n in line.split(',')]
            nums.sort()
            outfile.write(','.join([str(n) for n in nums]))
            outfile.write('\n')

【讨论】:

  • 我的老兄,非常感谢,真的!现在我将尝试理解它并为我编辑。
猜你喜欢
  • 2017-09-07
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
相关资源
最近更新 更多