【问题标题】:sorting a list by a certain letter and by alphabetical order按特定字母和字母顺序对列表进行排序
【发布时间】:2020-02-04 14:35:35
【问题描述】:
启动函数
def front_x(字):
# 你的代码在这里
return
结束函数
给定一个字符串列表,我想返回一个按排序顺序排列的字符串列表,除了首先将所有以“x”开头的字符串分组。我知道我可能需要按以“x”开头的单词然后按字母对列表进行排序,我就是无法返回代码。我在这方面还很新鲜。
【问题讨论】:
标签:
list
sorting
alphabetical
【解决方案1】:
将来尝试更好地表述您的问题并放置语言标签
这是完成任务的直接方法(它不需要优化)
def front_x(words): # your code here
words_starting_with_x=[]
words_not_starting_with_x=[]
for word in words:
if word[0]== "x":
words_starting_with_x.append(word)
else:
words_not_starting_with_x.append(word)
words_starting_with_x = sorted(words_starting_with_x) # there
words_not_starting_with_x = sorted(words_not_starting_with_x)
return words_starting_with_x + words_not_starting_with_x #+ operator does the concatenation for list
my_list=["hope_you_got_it!","x4_place","x2_is_not","x3_a","x5_to_do","x6_your","x7_exercises","x1_stackoverflow","some_other_words_bla_bla"]
front_x(my_list)
输出是:
['x1_stackoverflow',
'x2_is_not',
'x3_a',
'x4_place',
'x5_to_do',
'x6_your',
'x7_exercises',
'hope_you_got_it!',
'some_other_words_bla_bla']