Python随机数列表组织

2024-10-01 11:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

list = [37,20,3,2,66,5]
oglist = []
a = list[0]
while len(list) > 2:
    for i in list:
        if a <= i:
            continue
        else :
            a = i
            continue
    oglist.append(a)
    list.pop(list.index(a))
print(oglist) 

我一直在犯错误列表.pop说x不在列表中


Tags: in列表forindexlenifpopelse
2条回答

如注释中所述,您正在重写类名list。 我看到的另一个问题是a不是每次遍历循环时都重置的:在第一次遍历之后,a的值是66,并且一直保持66直到结束。你知道吗

randomList = [37,20,3,2,66,5]
sortedList = []
while len(randomList) > 0:
    a = randomList[0]
    for i in randomList:
        if a <= i:
            continue
        else :
            a = i
            continue
    sortedList.append(a)
    randomList.pop(randomList.index(a))
print(sortedList)

我将a = randomList[0]移动到while循环中,这样a的值总是列表中某个元素的值。
我还将条件更改为len(randomList)>0,以便继续排序,直到参数列表为空

如果我了解你的主要问题,这是一个简单的解决办法。你知道吗

import random
lists = []
for a in range(10):
    lists.append(random.randint(1, 10))

print "lists",sorted(lists)

相关问题 更多 >