我正在尝试根据它们之间的空格在python中排序字符串列表。例如,如果字符串列表是{'hello world', 'hello', 'hello world again', 'hello there'}.
订购后,列表应包含第一个位置中空格数最多的字符串,其后包含其他字符串:
{'hello world again', 'hello world', 'hello there', 'hello'}.
此致 阿洛克
答案 0 :(得分:5)
代表list
:
>>> list.sort(key=lambda x: x.count(' '), reverse=True)
# list = ['hello world again', 'hello world', 'hello there', 'hello']
代表set
:
>>> sorted(set, key=lambda x: x.count(' '), reverse=True)
# ['hello world again', 'hello world', 'hello there', 'hello']
答案 1 :(得分:2)
无论是设置还是列表,您都可以使用sum
作为sorted
功能的关键 -
d={'hello world', 'hello', 'hello world again', 'hello there'}
sorted(d,key = lambda x: sum(1 for space in d if space==" "))
OR
lst = ['hello world again', 'hello world', 'hello there', 'hello']
sorted(d,key = lambda x: sum(1 for space in l if space==" "))
输出 -
['hello world again', 'hello world', 'hello there', 'hello']
答案 2 :(得分:-1)
最好是向Sub GoodREPLACETeleModule()
Dim wFind As Long
' <PUTDESCRIPTIONHERE>
For MY_ROWS = 1 To Range("AF" & Rows.Count).End(xlUp).Row
MsgBox "Row " & MY_ROWS
wFind = InStr(Range("R" & MY_ROWS).Value, "PUTDESCRIPTIONHERE")
If wFind = 0 Then
MsgBox "Nothing to replace"
Else
a = Len(Range("R" & MY_ROWS).Value): b = Len(Range("AF" & MY_ROWS).Value)
Range("R" & MY_ROWS).Value = Replace(Range("R" & MY_ROWS).Value, "PUTDESCRIPTIONHERE", Range("AF" & MY_ROWS).Value)
wFind = InStr(Range("R" & MY_ROWS).Value, "PUTDESCRIPTIONHERE")
If Not wFind = 0 Then MsgBox "Replace Failed"
If Len(Range("R" & MY_ROWS).Value) < a + b - Len("PUTDESCRIPTIONHERE") Then
MsgBox "The replace did not happen successfully"
Else
If Len(Range("R" & MY_ROWS).Value) > 32766 then
Msgbox "Too many characters"
Else
MsgBox "Replace succeeded, old string was " & a & " characters, new string is " & Len(Range("R" & MY_ROWS).Value) & " characters."
End If
End If
End If
Next MY_ROWS
' <PUTIMAGEHERE>
For MY_ROWS = 1 To Range("AF" & Rows.Count).End(xlUp).Row
MsgBox "Row " & MY_ROWS
wFind = InStr(Range("P" & MY_ROWS).Value, "PUTIMAGEHERE")
If wFind = 0 Then
MsgBox "Nothing to replace"
Else
a = Len(Range("R" & MY_ROWS).Value): b = Len(Range("AF" & MY_ROWS).Value)
Range("P" & MY_ROWS).Value = Replace(Range("P" & MY_ROWS).Value, "PUTIMAGEHERE", Range("AF" & MY_ROWS).Value)
wFind = InStr(Range("P" & MY_ROWS).Value, "PUTIMAGEHERE")
If Not wFind = 0 Then MsgBox "Replace Failed"
If Len(Range("P" & MY_ROWS).Value) < a + b - Len("PUTIMAGEHERE") Then
MsgBox "The replace did not happen successfully"
Else
If Len(Range("P" & MY_ROWS).Value) > 32766 then
Msgbox "Too many characters"
Else
MsgBox "Replace succeeded, old string was " & a & " characters, new string is " & Len(Range("P" & MY_ROWS).Value) & " characters."
End If
End If
End If
Next MY_ROWS
End Sub
或cmp
提供您自己的.sort()
参数
sorted()
答案 3 :(得分:-1)
简单的解决方案:
ll = ['hello world again', 'hello world', 'hello there', 'hello']
sorted(ll,reverse=True)
['hello world again', 'hello world', 'hello there', 'hello']
你不需要lambda或其他东西 - 它是正常的排序顺序