我有一個類似的串列:
barcode = ["13350V1","13350V10","13350V2","13350V20"]
我想根據最后三位數字對這個串列進行排序,所以結果是:
newbarcode = ["13350V1","13350V2","13350V10","13350V20"]
現在我可以使用下面的腳本來執行此操作,但我不確定這是什么意思 (x: str(x)[-3]),并感謝您在這方面的幫助。
newbarcode = sorted(barcode, key=lambda x: str(x)[-3])
uj5u.com熱心網友回復:
找到V字串中的位置,然后對之后的所有數字進行排序,但用 0 填充它們以進行自然排序:
barcode = ['13350V1','13350V10','13350V2','13350V20']
newbarcode = sorted(barcode, key=lambda x: x[x.rindex('V') 1:].zfill(5))
print(newbarcode)
# Output
['13350V1', '13350V2', '13350V10', '13350V20']
更新
str(x)[-3] 是什么意思?
假設數字1357900:
>>> n
1357900
# Convert number to string
>>> str(n)
'1357900'
# Now get the third character from the end (negative indexing)
>>> str(n)[-3]
'9'
# Slice the string from the third character from the end to end
>>> str(n)[-3:]
'900'
uj5u.com熱心網友回復:
對于更復雜的任務,如果你創建一個方法而不是一個神奇的單行 lambda,你可能會更好地理解:
def sortbyend(x: str) -> int:
pieces = x.split("V")
last_piece = pieces[-1]
number = int(last_piece)
return number
barcode = ["13350V1","13350V2","13350V10","13350V20"]
newbarcode = sorted(barcode, key=sort_by_end)
print(newbarcode)
這樣,您就可以在該函式在key屬性中使用之前單獨理解、測驗和除錯該函式。
一旦你理解了 lambdas 并且更熟悉它們,你可以將它轉換為 lambdas:
newbarcode = sorted(barcode, key=lambda x: int(x.split("V")[-1]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/408340.html
標籤:
