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

标签 python python-2.7

当给定 ['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/

相关文章:

python - 与 Python 控制系统库相比,SciPy 的 lsim 的行为不符合预期

python-2.7 - 使用 scikit-learn 去除低方差特征

Python CSV文件增量读写

用于学习 Django 的 Python 2.7 或 3.3

python - 由于 EXTENSION 数组为空,PIL 的保存功能中出现“未知扩展名”

python - 如何在Python中查找字符串中所有出现的子字符串

python - 带有 Gunicorn Dockerized 的 Flask 应用程序,监听 : http://0. 0.0.0 :8000, 但 URL 没有响应

python - 如何在同一行(shell 或窗口)中每次使用不同的输出重新打印 2D 数组或多个输出 [Python 3.x]?

python - 使用相同的装饰器路由到 view_func "flask"

python - Python 2.7 中从另一个类方法调用一个类方法