[英]Reverse list of strings python [One Liner]
我正在嘗試反轉字符串列表。 例如
一二三
將輸出為
三二一
我已經試過了
[x for x in range(input()) [" ".join(((raw_input().split())[::-1]))]]
但我收到一個錯誤:
TypeError: list indices must be integers, not str
>>> ' '.join("one two three".split()[::-1])
'three two one'
你可以這樣使用
>>> ' '.join(raw_input().split()[::-1])
one two three
'three two one'
>>> t="one two three"
>>> " ".join( reversed(t.split()) )
'three two one'
如果要使用raw_input()
嘗試以下操作:
>>> " ".join((raw_input().split())[::-1])
one two three
'three two one'
為了真正解決您的代碼以及為什么它會因錯誤而失敗,您正在嘗試使用str
" ".join((raw_input().split()[::-1]))
為范圍列表建立索引:
range(input())[" ".join((raw_input().split()[::-1]))]
您將需要遍歷內部列表,以使代碼運行時不會出錯:
[s for x in range(input()) for s in [" ".join((raw_input().split()[::-1]))]]
這將輸出類似:
2
foo bar
foob barb
['bar foo', 'barb foob']
並且可以簡化為:
[" ".join((raw_input().split()[::-1])) for _ in range(input())]
如果您只想在外部列表上調用join一個字符串,我也建議您使用int(raw_input(...
通常,但是我知道您在打高爾夫球。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.