简体   繁体   中英

Compare two strings and return bigger items in each - Python

I have two equal-length strings, which are part of two lists a and b , they look like this:

a[1] = '0   8 9'
b[1] = '0 * 5 6'

I want to compare each items in each string above in order (by ASCII code), also for the rest of the list a and b .

My expect result for these 2 strings would be:

'0 * 8 9'

I'm new to Python, I have read about list comprehension but I don't know how to use that in this case. I need some help, thank you in advance!

EDIT: I have to compare non-numeric values. So I have to compare them by ASCII code. (I make some changes the questions)

''.join(map(max, a, b))

Demo:

>>> a = '0   8 9'
>>> b = '0 * 5 6'
>>> ''.join(map(max, a, b))
'0 * 8 9'

Note : below is in case of the requirements being for comparision of numbers only (before the OP's edit). For the OP's new requirements, check @StefanPochmann's answer

Using list comprehension :

>>> [ max(map(int,ele)) for ele in zip(a.split(),b.split()) ]

#driver values :

IN : a  = '0 1 8 9' 
IN : b = '0 4 5 6'
OUT : [0, 4, 8, 9]

Next is easy. Just join them. So, finally :

>>> l = [ str(max(map(int,ele))) for ele in zip(a.split(),b.split()) ]   
>>> ' '.join(l)

#driver values :

IN : a  = '2 1 8 9'
IN : b = '11 4 5 6'
OUT : '11 4 8 9'

IMP : The map here takes care of situations involving finding of max between numbers like [2, 11] , where without it, it would chose 2 (as its max in string chronological order)

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