我有一个列表listOfNumbers = [3,2,1,4,5,6,7,8,9,22,25,16,17,28]
,我想按升序对该列表进行排序,但首先是奇数,然后是偶数,如下所示:
[1, 5, 7, 9, 11, 15, 19, 29,'startOF->evens', 4, 8, 10, 14, 16, 28, 32, 66]
没有排序功能
我已经尝试过了,但是出现错误
data_list = [3,2,1,4,5,6,7,8,9,22,25,16,17,28]
new_list = []
while data_list:
minimum = data_list[0]
for x in data_list:
if x < minimum:
minimum = x
new_list.append(minimum)
data_list.remove(minimum)
print (new_list)
def Huhu(data_list):
ev_li = ''
od_li = ''
for i in data_list:
if (i % 2 == 0):
ev_li.append(i)
else:
od_li.append(i)
print(new_list,od_li "startOF->evens",ev_li)
感谢我所做的回复
data_list = [3,2,1,4,5,6,7,8,9,22,25,16,17,28]
new_list = []
while data_list:
minimum = data_list[0] # arbitrary number in list
for x in data_list:
if x < minimum:
minimum = x
new_list.append(minimum)
data_list.remove(minimum)
odds = []
evens = []
for i in new_list:
if i % 2 == 0:
evens.append(i)
else:
odds.append(i)
print(odds,"startOF->evens", evens)
答案 0 :(得分:5)
您可以将sorted
与自定义key
参数一起使用进行排序。
>>> sorted(listOfNumbers, key=lambda i: (i%2==0, i))
[1, 3, 5, 7, 9, 17, 25, 2, 4, 6, 8, 16, 22, 28]
在这种情况下,您可以先按奇/偶排序,然后按值本身排序。
答案 1 :(得分:0)
如果您想知道代码为什么失败:
data_list = [3,2,1,4,5,6,7,8,9,22,25,16,17,28]
new_list = []
while data_list:
minimum = data_list[0]
for x in data_list:
if x < minimum:
minimum = x
new_list.append(minimum)
data_list.remove(minimum)
print (new_list)
def Huhu(data_list):
ev_li = list()
od_li = list()
for i in data_list:
if (i % 2 == 0):
ev_li.append(i)
else:
od_li.append(i)
print(new_list,od_li, "startOF->evens",ev_li)
您有三个错误:
首先:缩进问题:
def Huhu(data_list):
ev_li = ''
od_li = '' <- Here
第二个:这里缺少逗号:
print(new_list,od_li [here] "startOF->evens",ev_li)
第三:
ev_li和od_li必须为list
但是可以肯定@CoryKramer是更干净的:P