AttributeError: 'int' object has no attribute 'split'

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

I'm doing the merge sort in python but I have a problem. When I try to insert the list from the console (one number per line which return a list of string) I cannot convert it in integers. Can you help me understanding the problem.

import sys  def mergeSort(lista):     res = []     for i in lista[0].split():         res.append(int(i))     if len(res)>1:         mid = len(res)//2         lefthalf = res[:mid]         righthalf = res[mid:]         mergeSort(lefthalf)         mergeSort(righthalf)         i=0         j=0         k=0         while i<len(lefthalf) and j<len(righthalf):             if lefthalf[i]<righthalf[j]:                 res[k]=lefthalf[i]                 i=i+1             else:                 res[k]=righthalf[j]                 j=j+1             k=k+1          while i<len(lefthalf):             res[k]=lefthalf[i]             i=i+1             k=k+1          while j<len(righthalf):             res[k]=righthalf[j]             j=j+1             k=k+1     print(res)  alist = [] for l in sys.stdin:     alist.append(l.strip()) mergeSort(alist)

The code error says: AttributeError: 'int' object has no attribute 'split' The input is a file (given from the shell with the command: "python3 merge.py < data.txt") with the list of numbers one per line. Example: 2 3 0 12 11 7 4 Should return 0 2 3 4 7 11 12 Of course I don't have an output because of the error

回答1:

You're converting a list of strings to a list of integers at the top of your mergeSort routine. The subsequent recursive calls to mergeSort are trying to do the same, except now to lists of integers.

You should handle all file parsing completely separate from your mergeSort routine which should be designed just to work on a list of numbers. This is a "separation of concerns".



回答2:

If you also want the index, you can use enumerate:

data = ['itemA', 'itemB', 'itemC', 'itemD'] for (i, item) in enumerate(data):     print("Item #%d is %s" % (i, str(item)))

For future reference, you can debug like so:

def mergeSort(lista):     res = []     print(lista)     for i in lista[0].split():         print(i)         res.append(int(i))


回答3:

It should be for i in lista rather than for i in lista[0].split(), and you can simply achieve it by list comprehension: res = [int(num) for num in lista]



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!