反向字符串列表 python [One Liner]

Reverse list of strings python [One Liner]

我正在尝试反转字符串列表。例如

one two three

将输出为

three two one

我试过了

[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'

如果您想使用 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(...,但我知道您在打代码。

>>> t="one two three"
>>> " ".join( reversed(t.split()) )
'three two one'