我的清单有问题。我有一个list =['randomf','decisiont','extremeg']
附有另一个列表的list2 = ['bike','age','car'],
,然后根据它进行排序,这意味着第一个列表的每个值都具有的附加值,list2(e.g:'randomf_bike','randomf_age' ,'randomf_car')
但是当我排序时,它变成这样(例如:'randomf_age','randomf_bike' ,'randomf_car') Its
不仅根据该列表的第一个字母进行排序值,还可以根据“ _”后面的字母进行排序。如何根据第一个字母进行排序?
My code:
list =['randomf','decisiont','extremeg']
list2 = ['bike','age','car']
new_list = [el1+'_'+el2 for el2 in list2 for el1 in sorted(set(list))]
new_list = sorted(new_list)
which gives : new_list = ['decisiont_age','decisiont_bike' ,'decisiont_car','extremeg_age','extremeg_bike' ,'extremeg_car','randomf_age','randomf_bike' ,'randomf_car']
The excepted output is:
new_list = ['decisiont_bike','decisiont_age' ,'decisiont_car','extremeg_bike','extremeg_age' ,'extremeg_car', 'randomf_bike','randomf_age' ,'randomf_car']
您可以给key
调用函数sorted
。如果只想对字符串中第一个_
字符之前的部分进行排序,则可以执行sorted(new_list, key=lambda s: s.split('_', 1)[0])
。
但是,如果从一开始就以正确的顺序组装复合字符串,那么您也可以避免第二种排序。我认为您可以更改两级迭代的顺序,它应该与您想要的相匹配(您已经在对第一个列表进行排序):
new_list = [el1+'_'+el2 for el1 in sorted(set(list)) for el2 in list2] # change order here
# don't sort again!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句