(Python) 如何反转列表项的字符
我想反转列表中每个项目的字符顺序
myList = ['78', '79', '7a']
并且我希望它获得输出 87 97 a7到目前为止
我已经尝试过:
newList = [x[::-1] for x in myList][::-1]
这
def reverseWord(word):
return word[::-1]
myList = ['78', '79', '7a']
newList = [reverseWord(word) for word in myList]
将返回原始列表或反转整个列表而不仅仅是项目
I want to reverse character order of every item in a list
I have myList = ['78', '79', '7a']
and I want it to get the output 87 97 a7
so far I've tried:
newList = [x[::-1] for x in myList][::-1]
and
def reverseWord(word):
return word[::-1]
myList = ['78', '79', '7a']
newList = [reverseWord(word) for word in myList]
this would either return the original list or reverse the entire list and not just the items
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的行
[x[::-1] for x in myList][::-1]
中,最后的[::-1]
确实反转了列表,你不需要它你缺少的只是格式:使用空格连接元素
In your line
[x[::-1] for x in myList][::-1]
, the final[::-1]
does reverse the list, you don't need itWhat you missing is only formatting : join the element using a space
由于您尝试仅反转列表中的项目而不是列表本身,因此您只需要删除额外的
[::-1]
,因此您的代码应如下所示:使用
reverseWord
方法的第二个代码是正确的,并且可以准确地为您提供所需的输出。Since your trying to reverse only the items inside the list and not the list it-self you only need to remove the extra
[::-1]
,so your code should look like this:In addition your second code using the
reverseWord
method is correct and gives you exactly the output you wanted.好吧,一句话就能完成这项工作:
Well, a one-liner to do the job :