簡體   English   中英

如何反轉 python 中的子列表

[英]How to reverse a sublist in python

給定以下列表:

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

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

誰能幫我如何將它加入實際列表並帶來預期的 output

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

我相信你需要兩行代碼,首先拆分值:

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

哪個返回:

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

然后恢復訂單:

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

哪個返回:

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

您可以使用以下簡單的理解:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM