如何使用python以递增顺序编写数字列表

时间:2018-04-30 07:57:09

标签: python sorting odoo-8

我有一个清单

a1 = ['1', '5-10', '12', '18', '23', '100-110', '16-17', '20']

我希望这个元素列表按顺序递增 喜欢

a1 = ['1','5-10','12','16-17','18','20','23','100-110']

请有人帮我安排这个

case = ['1', '5-10', '12', '18', '23', '100-110', '16-17', '20']
case1 = [i.split('-', 1)[0] for i in case]
case1 = [int(x) for x in case1]

case1.sort()

打印后,case1输出为

[1, 5, 12, 16, 18, 20, 23 ,100]

但我想输出就像

[1, 5-10, 12, 16-17, 18, 20, 23, 100-110]

1 个答案:

答案 0 :(得分:0)

如果你确定每个列表元素应该是整数字符串或整数字符串分隔的字符串复合,你可以尝试这样的事情:

a_dict = {int(v.split('-')[0]): v for v in a}
final_a = [a_dict[k] for k in sorted(a_dict)]
print final_a

返回

  

[' 1',' 5-10',' 12',' 16-17',' 18&# 39;,' 20',' 23',' 100-110']