创建一个对两个列表进行排序的函数

Tyl*_*eed 0 python sorting list

我正在尝试创建一个函数,该函数返回已排序的字符串列表,但带有附加条件,该函数将对所有以w / 'x'first 开头的字符串进行排序。

因此,例如,列表['mix', 'xyz, 'apple', 'xanadu'] 将产生['xanadu', xyz', 'apple', 'mix']

def front_x(words):
    x = []
    y = []
    for k, v in enumerate(words):
        if v.startswith("x"):
            x.append(v)
        else:
            y.append(v)

    x.sort()
    y.sort()
    print(x.extend(y))

this_list = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']

front_x(this_list)
Run Code Online (Sandbox Code Playgroud)

这给了我输出None

yat*_*atu 6

您可以使用sorted以下内容key

l = ['mix', 'xyz', 'apple', 'xanadu']

sorted(l, key=lambda x: (x[0]!='x', x))
# ['xanadu', 'xyz', 'apple', 'mix']
Run Code Online (Sandbox Code Playgroud)

或如@deepspace建议使用str.startswith

sorted(l, key=lambda s: (not s.startswith('x'), s))
Run Code Online (Sandbox Code Playgroud)

上面的键是基于元组对字符串进行排序,该元组包含由expression x[0]!='x'和字符串本身组成的布尔值:

[(x[0]!='x', x) for x in l]
# [(True, 'mix'), (False, 'xyz'), (True, 'apple'), (False, 'xanadu')]
Run Code Online (Sandbox Code Playgroud)

因此,排序的第一个标准是字符串是否以开头x(请记住FalseTrue0和评估1),然后是字符串本身以字母数字排序。