在Python中不使用.sorted()排序列表

1 投票
6 回答
6174 浏览
提问于 2025-04-16 13:05

我有一个列表 a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]

我想要得到一个新的列表 b = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2'],但是不想用 .sorted() 这个方法。

谢谢!

6 个回答

3

这看起来有点随意,不使用 sorted()。我想你是说,你不想按照默认的字母数字顺序来排序列表。

这里是如何定义一个排序的关键字,用来按花色和等级对表示扑克牌的字符串(从 a1 到 d13)进行排序:

>>> def cardsortkey(card):
...     return (card[0], int(card[1:]))
... 
>>> cardsortkey('a1')
('a', 1)
>>> a = ['a1', 'b1', 'c1', 'd1',
...      'a2', 'b2', 'c2', 'd2',
...      'a11', 'b11', 'c11', 'd11']
>>> sorted(a, key=cardsortkey)
['a1', 'a2', 'a11', 'b1', 'b2', 'b11', 'c1', 'c2', 'c11', 'd1', 'd2', 'd11']

这就是你需要的吗?

5

列表没有 .sorted() 这个方法,不过有一个 sorted() 函数,正如 S.Mark 提到的,它会返回一个新的排序后的列表。另外,还有一个 .sort() 方法,它会直接在原来的列表上进行排序,并且返回 None。如果你是想不使用 sorted() 函数的话,那么:

a = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2',]
a.sort()
b = a

否则,也许你可以进一步澄清一下你的问题。

0
l = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2']
numbersPerLetter = 2
lsorted = []
for i in range(len(l) / numbersPerLetter):
   lsorted.extend([l[x+i] for x in range(0, len(l), len(l) / numbersPerLetter)])
print(lsorted)

输出:

['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2']

在Python 3.X中,你需要把 / 改成 //,这样才能正常工作。

撰写回答