Сортировка списка кортежей с первым алфавитно-цифровым элементом кортежа - PullRequest
1 голос
/ 23 мая 2019

Я должен отсортировать этот список кортежей ниже на основе первого элемента в кортеже так, чтобы это

[ ('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')]

1 Ответ

1 голос
/ 23 мая 2019

Вы можете использовать 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')]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...