简体   繁体   中英

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.

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:

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?

Suppose the number 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:

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.

Once you understood lambdas and are more familiar with them, you can convert it to a lambda:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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