[英]Is there a shorter way to make this function?
B. front_x給定一個字符串列表,返回一個按排序順序排列的字符串列表,但首先將所有以'x'開頭的字符串分組。 例如['mix','xyz','apple','xanadu','aardvark']產生['xanadu','xyz','aardvark','apple','mix']提示:可以做到通過制作2個列表並在組合它們之前對它們進行排序。
def front_x(words):
xList = []
nonXList = []
for word in words:
if word[0] == 'x':
xList.append(word)
else:
nonXList.append(word)
return sorted(xList) + sorted(nonXList)
我是python和程序設計的新手,但我覺得有一種更緊湊的方式可以編寫此代碼,或者有一種更“ pythonic”的方式嗎?
我也試圖返回該行:
return xlist.sort() + nonXList.sort()
但這是錯誤的。 為什么會這樣呢?
您可以通過調用key
來對words
進行sorted
使用key
參數“示教” sorted
words
的項目進行排序:
def front_x(words):
return sorted(words, key=lambda word: (word[0] != 'x', word))
每個words
項調用一次key
函數,並返回一個代理值,通過該值可以對words
項進行排序。 tuples
例如上面的lambda
函數返回的tuples
,按字典順序排序(根據元組中的第一項,並根據第二個斷開關系)。
出色的Sorting Howto解釋了此技術以及其他技術。
例如,
print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']))
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
請注意,如果words
包含空字符串,則word[0]
將引發IndexError
。 相反, ''.startswith('x')
返回False
。 因此,如果您希望front_x
處理空字符串,請使用word.startswith('x')
如果希望front_x
,請使用word[0] == 'x'
。
使用清單理解
list = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
list.sort()
listA = [item for item in list if item[0] == 'x']
listB = [item for item in list if item[0] != 'x']
listC = listA + listB
這行得通,而且簡單易懂。
def front_x(words):
xlist = [item for item in words if item[0] =='x']
nonXList = [item for item in words if item[0] !='x']
xlist.sort() # The .sort() method sorts a list alphabetically
nonXList.sort()
Combined_Lists = xlist + nonXList
return Combined_Lists
#You can also comment Combined_Lists and
#just have return xlist + nonXList
由於您是Python的新手,所以我嘗試使其盡可能簡單。
您返回的錯誤是因為sort不返回值,它僅修改列表。
這似乎是一種相當快的方法,它以線性時間運行,您不會比這快得多。 話雖這么說,您可以通過內聯代碼來縮短它,但是這種方式並不總是可讀性強。
>>> l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> sorted ([x for x in l if x.startswith('x')]) + sorted([x for x in l if not x.startswith('x')])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
return sorted([w for w in words if w[0] == 'x']) + sorted([w for w in words if w[0] != 'x'])
該錯誤是因為.sort()
就位。 它返回None
,並且您不能做None + None
由於Python的排序是穩定的,因此您還可以通過執行兩種排序來完成此操作
>>> L = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> sorted(sorted(L), key=lambda x:x[0]!='x')
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
和就地版本
>>> L.sort()
>>> L.sort(key=lambda x:x[0]!='x')
>>> L
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.