python for 循环数组 int to str

我创建了一个数组,每次for循环的时候会报这个错误
'list' object cannot be interpreted as an integer

def sort(Lst):
newList = []
    map(str,Lst)
    for x in range(Lst):
        for j,y in enumerate(newList):
            if x > y :
                newList.insert(j,x.__str__())
        else:
            newList.append(x.__str__())


lst = [54,3,5,2,1]
print(sort(lst))

python range() 函数可创建一个整数列表,一般用在 for 循环中。你函数传进来的是列表呀,怎么用range。并且你的代码的缩进让人看不来你要实现什么,你可以修改一下缩进。但是目前你出现的问题就range的错误使用,如果你要用可以这样。for x in range(len(Lst)):、

更新回答

def sort(Lst):
    newList = [] 
    for x in range(len(Lst)):
        print(newList)
        newList.append(Lst[x])
        for y in range(len(newList)):
            if Lst[x]>newList[y] and x!=y:
                t=newList[x]
                newList[x]=newList[y]
                newList[y]=t

    return newList
lst = [54,3,5,515,85485,5415,2,1]
print(sort(lst))

结果
[]
[54]
[54, 3]
[54, 5, 3]
[515, 54, 5, 3]
[85485, 515, 54, 5, 3]
[85485, 5415, 515, 54, 5, 3]
[85485, 5415, 515, 54, 5, 3, 2]
[85485, 5415, 515, 54, 5, 3, 2, 1]

看了你的代码,首先你可能是重写sort,他是一个排序方法,说到排序,不得不提一下算法,排序有冒泡排序,顺序排序等,但是核心的就是找到最大最小罢了。按照你的代码我推测你的逻辑是这样,newList先为空,for判断错误,然后esle添加一个,第二次进入的时候,如果大于就Iinsert到该元素前面,但是如果是小于呢?你在代码中未做判断和处理,按照你的逻辑这里也应该加上一个newList.append(x.__str__()),将小的数添加在后面。但是问题在后面的循环就出现,你是用的INSERT,挨个去判断,如果大于就INSERT,但是当大于多个数据的时候呢,程序就会插入多个啊。逻辑存在问题,建议重新组织逻辑。排序排序,就是找最大最小的游戏,建议博主在学代码的同时,了解一下算法。

Python在使用for循环的时候不能修改循环中使用的变量,如果要想该变循环次数的话可以使用while语句

转载自这里:https://www.cnblogs.com/loveyou1314/p/8284618.html

str在哪里定义的,str应该是转化成字符串的函数,那么,x就是字符串,怎么又 x > y