2024-04-25 22:55:49 发布
网友
我有一份清单,其中包括
a= [june,32,may,67,april,1,dec,99]
我只想把数字按降序排列 但它应该显示相应的对:
Output Expected ---------------- dec,99,may,67,june,32,april,1
我试图在列表中使用a.sort(reverse=True)命令进行排序,但没有得到预期的输出,这一个很混乱。你知道吗
a.sort(reverse=True)
可以使用元组列表:
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:
itertools.chain
from itertools import chain res = list(chain.from_iterable(res)) ['dec', '99', 'may', '67', 'june', '32', 'april', '01']
您可以首先创建包含月值对的嵌套列表,应用sorted,然后展开:
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]
可以使用元组列表:
如果需要展平,请使用
itertools.chain
:您可以首先创建包含月值对的嵌套列表,应用
sorted
,然后展开:输出:
相关问题 更多 >
编程相关推荐