简体   繁体   English

按最后 3 位数字排序

[英]Sort by last 3 digits

I have a list like:我有一个类似的列表:

barcode = ["13350V1","13350V10","13350V2","13350V20"]

I want to sort this list based on the last three digits, so the result would be:我想根据最后三位数字对这个列表进行排序,所以结果是:

newbarcode = ["13350V1","13350V2","13350V10","13350V20"]

Now I am able to do this using the script below, but I am not exactly sure what does this mean (x: str(x)[-3] ) and appreciate your help in this regard.现在我可以使用下面的脚本来执行此操作,但我不确定这是什么意思 (x: str(x)[-3] ) 并感谢您在这方面的帮助。

newbarcode = sorted(barcode, key=lambda x: str(x)[-3])

Find the position of V in the string then sort on all digits after but pad them with 0 to have a natural sort:在字符串中找到V的 position 然后对之后的所有数字进行排序,但用 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']

Update更新

What does str(x)[-3] meaning? str(x)[-3] 是什么意思?

Suppose the number 1357900 :假设数字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'

For more complex tasks it might be better for you to understand if you create a method instead of a magic one line lambda:对于更复杂的任务,如果你创建一个方法而不是一个神奇的一行 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)

That way you can understand and test and debug the function individually before it gets used in the key property.这样您就可以在将 function 用于key属性之前单独理解、测试和调试它。

Once you understood lambdas and are more familiar with them, you can convert it to a lambda:一旦你理解了 lambdas 并且更加熟悉它们,你可以将它转换为 lambda:

newbarcode = sorted(barcode, key=lambda x: int(x.split("V")[-1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM