Bat*_*rum 2 python sorting list
我试图根据它是奇数还是偶数(甚至获得更高的优先级)对数字列表进行排序.例:
a=[1,2,3,4]
a.sort(key=org(a)) sorted will produce [2,4,1,3]. I want to use the sort method
def org(a):
for i in range(len(a)):
if a[i]%2==0:
b.append(a[i])
b.sort()
else:
c.append(a[i])
c.sort()
print(b+c)
Run Code Online (Sandbox Code Playgroud)
我从运行a.sort(key = org(a))收到此错误
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
a.sort(key=org(a))
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)
我意识到每次排序都会让它变慢.我可以采用哪种方式而不必在每次循环后进行排序?
要按"均匀度"排序,然后按幅度排序,您可以使用返回a的函数 tuple
>>> a=[1,2,3,4]
>>> a.sort(key=lambda x: (x % 2, x))
>>> a
[2, 4, 1, 3]
Run Code Online (Sandbox Code Playgroud)
要首先对奇数条目进行排序,您可以简单地否定模数的值.这是一种有用的技巧,可以反转一般的数字字段.
>>> a.sort(key=lambda x:(-(x % 2), x))
>>> a
[1, 3, 2, 4]
Run Code Online (Sandbox Code Playgroud)