写这个表达式的更pythonic方式?

hel*_*hod 8 python sorting

我应该采用一个单词列表并对其进行排序,除非我需要将所有以'x'开头的字符串分组.

这是我得到的:

list_1 = []
list_2 = []

for word in words:
  list_1.append(word) if word[0] == 'x' else list_2.append(word)

return sorted(list_1) + sorted(list_2)
Run Code Online (Sandbox Code Playgroud)

但我觉得有一种更优雅的方式可以做到这一点......

编辑

示例: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']收益率['xanadu', 'xyz', 'aardvark', 'apple', 'mix'].

Sil*_*ost 41

>>> words = ['xoo', 'dsd', 'xdd']
>>> sorted(words, key=lambda x: (x[0] != 'x', x))
['xdd', 'xoo', 'dsd']
Run Code Online (Sandbox Code Playgroud)

说明:key函数返回一对(元组).第一个元素是FalseTrue,取决于字符串中的第一个字符是否为'x'.False之前排序True,因此以开头的字符串'x'将在排序输出中排在第一位.元组中的第二个元素将用于比较第一个元素中相同的两个元素,因此所有以字母开头的字符串'x'将在它们之间进行排序,并且所有不以其开头的字符串'x'将在它们之间进行排序.

  • 我会使用`不是x.startswith('x')`而不是`x [0]!='x'`.假设没有一个词是''',我感到不安. (7认同)

Gle*_*ard 9

第一:当你的意思是"干净"时停止说"pythonic".这只是一个俗气的流行语.

不要使用那样的三元表达; 它意味着用作表达式的一部分,而不是用作流控制.这更清洁:

for word in words:
    if word[0] == 'x':
        list_1.append(word)
    else:
        list_2.append(word)
Run Code Online (Sandbox Code Playgroud)

你可以多改进一点 - 使用这样的三元表达式很好:

for word in words:
    target = list_1 if word[0] == 'x' else list_2
    target.append(word)
Run Code Online (Sandbox Code Playgroud)

如果words是容器而不是迭代器,您可以使用:

list_1 = [word for word in words if word[0] == 'x']
list_2 = [word for word in words if word[0] != 'x']
Run Code Online (Sandbox Code Playgroud)

最后,我们可以废弃整个事情,而是使用两种:

result = sorted(words)
result = sorted(result, key=lambda word: word[0] != 'x')
Run Code Online (Sandbox Code Playgroud)

首先进行正常排序,然后使用Python排序的稳定属性将以"x"开头的单词移动到前面,而不另行更改顺序.

  • 关于"pythonic"这个词:这里的评论中有一些有趣的讨论:http://nedbatchelder.com/blog/201011/pythonic.html (8认同)
  • pythonic!=干净; pythonic>干净 (5认同)
  • @flow:有效并不意味着干净或自然.请注意,在函数调用参数周围放置空格将使人们很难认真对待清晰代码. (4认同)
  • 我认为三元表达式的使用是完全有效的.人们甚至可以写`(list_1 if word [0] =='x'else list_2).append(word)`更清楚. (2认同)

dem*_*mas 6

words = ['xoo', 'dsd', 'xdd']
list1 = [word for word in words if word[0] == 'x']
list2 = [word for word in words if word[0] != 'x']
Run Code Online (Sandbox Code Playgroud)


akd*_*dom 5

应该注意的sorted是在Python 2.4中添加了.如果您希望更短的版本更清洁,更向后兼容,您可以.sort()直接使用该功能list. 还应该注意,x[0]在这种情况下使用样式数组索引语法时,空字符串将引发异常(正如许多示例所示). .startswith()应该使用,正如Tony Veijalainen的回答中所使用的那样.

>>> words = ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark']
>>> words.sort(key=lambda x: (not x.startswith('x'), x))
>>> words
['xanadu', 'xyz', '', 'aardvark', 'apple', 'mix']
Run Code Online (Sandbox Code Playgroud)

唯一的缺点是你正在改变给定的对象.这可以通过预先切片列表来解决.

>>> words = ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark']
>>> new_words = words[:]
>>> new_words.sort(key=lambda x: (not x.startswith('x'), x))
>>> new_words
['xanadu', 'xyz', '', 'aardvark', 'apple', 'mix']
>>> words
['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark']
Run Code Online (Sandbox Code Playgroud)