按某个字母和字母顺序对列表进行排序

时间:2020-02-04 14:35:35

标签: list sorting alphabetical

开始功能

def front_x(words): #您的代码在这里

return

结束功能

给出一个字符串列表,我想返回一个按排序顺序排列的字符串列表,除了首先对所有以'x'开头的所有字符串进行分组。我知道我可能需要按以'x'开头的单词然后按字母排序列表,我只是无法返回代码。我对此仍然很新鲜。

1 个答案:

答案 0 :(得分:0)

将来尝试更好地表达您的问题并放置语言标签

这是完成任务的直接方法(它不一定经过优化)

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']