简体   繁体   中英

Python: Split Integers and Strings in Lists

>>>list = []
>>>stringsandnumbers = input('Enter in the values. For example, "A=3,B=2,C=1,D=5"... ').split(',')
>>>list.append(stringsandnumbers)
>>>list.sort()
>>>print(list)

[[A=3,B=2,C=1,D=5]]

The problem with this is that it is not sorting the list from min to max. I'm not sure if splitting/separating it would be a good idea or if there's a way to just sort the numbers from the list? Any help would be appreciated.

Think you mean this,

>>> s = "A=3,B=2,C=1,D=5"
>>> sorted(s.split(','), key = lambda m: int(m.split('=')[1]))
['C=1', 'B=2', 'A=3', 'D=5']
>>> ','.join(sorted(s.split(','), key = lambda m: int(m.split('=')[1])))
'C=1,B=2,A=3,D=5'

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