我想要反转字符串列表。例如字符串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
我想要反转字符串列表。例如字符串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
要真正解决您的代码和失败的原因与错误,您正在试图指数范围列表,并附有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())]
如果你想要一个字符串就叫加入外名单上,我会一般也建议使用int(raw_input(...
,但我知道你是代码打高尔夫球。
感谢您的好解释:) – saleem
@saleem。不用担心,不用客气 –
>>> ' '.join("one two three".split()[::-1])
'three two one'
你可以使用这样的,
>>> ' '.join(raw_input().split()[::-1])
one two three
'three two one'
可能有助于实际解释为什么OP的代码不起作用 –
这已经在代码中,当我创建单行代码时它会引发类型错误。我正在尝试codegolf坦诚 – saleem
如果你想使用raw_input()
试试这个:
>>> " ".join((raw_input().split())[::-1])
one two three
'three two one'
>>> t="one two three"
>>> " ".join(reversed(t.split()))
'three two one'
的可能重复[我怎样才能扭转在Python列表?(http://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python) – rfj001
你想结果在一个字符串或列表 – NendoTaka
我需要在单行中实现这一点,并需要输出为字符串。我知道要扭转一个字符串。问题是当我尝试创建单行代码时。 – saleem