在python中只对特定索引进行排序,并使用相应的pai

2024-04-25 22:55:49 发布

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

我有一份清单,其中包括

a= [june,32,may,67,april,1,dec,99]

我只想把数字按降序排列 但它应该显示相应的对:

Output Expected
----------------
dec,99,may,67,june,32,april,1

我试图在列表中使用a.sort(reverse=True)命令进行排序,但没有得到预期的输出,这一个很混乱。你知道吗


Tags: 命令true列表output排序数字sortmay
2条回答

可以使用元组列表:

a = ['june', '32', 'may', '67', 'april', '01', 'dec', '99']

zipper = zip(a[::2], a[1::2])

res = sorted(zipper, key=lambda x: -int(x[1]))  # or, int(x[1]) with reverse=True

print(res)

[('dec', '99'), ('may', '67'), ('june', '32'), ('april', '01')]

如果需要展平,请使用itertools.chain

from itertools import chain

res = list(chain.from_iterable(res))

['dec', '99', 'may', '67', 'june', '32', 'april', '01']

您可以首先创建包含月值对的嵌套列表,应用sorted,然后展开:

a= ['june',32,'may',67,'april',01,'dec',99]
new_a = sorted([[a[i], a[i+1]] for i in range(0, len(a), 2)], key=lambda x:x[-1], reverse=True)
final_a = [i for b in new_a for i in b]

输出:

['dec', 99, 'may', 67, 'june', 32, 'april', 1]

相关问题 更多 >