简体   繁体   中英

How to reverse a sublist in python

Given the following list:

a = ['aux iyr','bac oxr','lmn xpn']

c = []
for i in a:
    x = i.split(" ")
    b= x[1][::-1] --- Got stuck after this line

Can anyone help me how to join it to the actual list and bring the expected output

output = ['aux ryi','bac rxo','lmn npx']

I believe you need two lines of codes, first splitting the values:

b = [x.split() for x in a]

Which returns:

[['aux', 'iyr'], ['bac', 'oxr'], ['lmn', 'xpn']]

And then reverting the order:

output = [x[0] +' '+ x[1][::-1] for x in b]

Which returns:

['aux ryi', 'bac rxo', 'lmn npx']

You can use the following simple comprehension:

[" ".join((x, y[::-1])) for x, y in map(str.split, a)]
# ['aux ryi', 'bac rxo', 'lmn npx']

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