gpt4 book ai didi

python - 需要对给定的字符串进行排序(首先以 x 开头的字符串)

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:03 25 4
gpt4 key购买 nike

当给定 ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] 列表时,代码不会返回最后一个词。

def front_x(words):
x_list = []
no_x_list = []
[x_list.append(i) for i in words if i[0] == "x"]
[no_x_list.append(words[i2]) for i2 in range(len(words)-1) if words[i2] not in x_list]
x_list.sort()
no_x_list.sort()
return x_list + no_x_list
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])

必须是:

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

使用列表 ['bbb', 'ccc', 'axx', 'xzz', 'xaa']['ccc', 'bbb', 'aaa', 'xcc', 'xaa'] 一切正常 ['xaa', 'xzz', 'axx', 'bbb', 'ccc']['xaa ', 'xcc', 'aaa', 'bbb', 'ccc']

最佳答案

迭代 range(len(words)-1) 看起来不正确。更重要的是,使用列表理解来添加列表是非常非Python的; list comps 用于构建列表而不进行列表追加,这在此处相当讽刺

您可以通过基于二元组的排序来执行一次排序,该二元组的第一项检查单词是否以 startswith 'x' 并将它们放在前面。元组中的第二项对列表应用词典排序,打破平局:

def front_x(words):
return sorted(words, key=lambda y: (not y.startswith('x'), y))

print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

关于python - 需要对给定的字符串进行排序(首先以 x 开头的字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com