【问题标题】:Sorting a list of tuples with the first tuple item being alphanumeric对元组列表进行排序,其中第一个元组项是字母数字
【发布时间】:2023-03-05 23:22:01
【问题描述】:

我必须根据元组中的第一项对下面的元组列表进行排序,以便

[ ('1 a', 'thisis1a'),
 ('1 b', 'thisis1b'),
 ('4', 'thisis4'),
 ('3', 'thisis3'), 
 ('2a', 'thisis2a')
 ]

changes to: 

[ ('1 a', 'thisis1a'),
 ('1 b', 'thisis1b'),
 ('2a', 'thisis2a'),
 ('3', 'thisis3'), 
 ('4', 'thisis4')
 ]

我尝试了以下代码,但没有成功:

from operator import itemgetter
sorted(showlist, key=itemgetter(1))

我也试过这个:

q=sorted(showlist,key=lambda item: (int(item.partition(' ')[0])
                               if item[0].isdigit() else float('inf'), item))

但没用。

顺便说一下,这是我的实际清单:

lists=[('1', 'no'),
 ('10', 'nan'),
 ('11', '["I\'m still a student and \xa0I am retraining."]'),
 ('12', 'nan'),
 ('14', 'no'),
 ('15', 'nan'),
 ('16', 'no'),
 ('17', 'nan'),
 ('18', '["I\'m still as student"]'),
 ('19 a', 'nan'),
 ('19 b', 'nan'),
 ('20 a', '["I\'m still a student member.\xa0"]'),

 ('69', 'nan'),
 ('7 a', '["Other"]'),
 ('7 b', 'nan'),
 ('72', 'nan'),
 ('8', 'nan'),
 ('9', 'yes')]

【问题讨论】:

    标签: python python-3.x sorting tuples


    【解决方案1】:

    你可以使用re.findall:

    import re
    lists = [('1', 'no'), ('10', 'nan'), ('11', '["I\'m still a student and \xa0I am retraining."]'), ('12', 'nan'), ('14', 'no'), ('15', 'nan'), ('16', 'no'), ('17', 'nan'), ('18', '["I\'m still as student"]'), ('19 a', 'nan'), ('19 b', 'nan'), ('20 a', '["I\'m still a student member.\xa0"]'), ('69', 'nan'), ('7 a', '["Other"]'), ('7 b', 'nan'), ('72', 'nan'), ('8', 'nan'), ('9', 'yes')]
    new_result = sorted(lists, key=lambda x:[int(re.findall('^\d+', x[0])[0]), x])
    

    输出:

    [('1', 'no'), 
     ('7 a', '["Other"]'), 
     ('7 b', 'nan'),   
     ('8', 'nan'), 
     ('9', 'yes'), 
     ('10', 'nan'), 
     ('11', '["I\'m still a student and \xa0I am retraining."]'), 
     ('12', 'nan'), 
     ('14', 'no'), 
     ('15', 'nan'), 
     ('16', 'no'), 
     ('17', 'nan'), 
     ('18', '["I\'m still as student"]'), 
     ('19 a', 'nan'), 
     ('19 b', 'nan'), 
     ('20 a', '["I\'m still a student member.\xa0"]'), 
     ('69', 'nan'), 
     ('72', 'nan')]
    

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多