(Python) 如何反转列表项的字符

发布于 2025-01-09 09:23:17 字数 452 浏览 0 评论 0原文

我想反转列表中每个项目的字符顺序

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

[旋木] 2025-01-16 09:23:17

在您的行 [x[::-1] for x in myList][::-1] 中,最后的 [::-1] 确实反转了列表,你不需要它

你缺少的只是格式:使用空格连接元素

myList = ['78', '79', '7a']
res = " ".join(x[::-1] for x in myList)
print(res)  # 87 97 a7

In your line [x[::-1] for x in myList][::-1], the final [::-1] does reverse the list, you don't need it

What you missing is only formatting : join the element using a space

myList = ['78', '79', '7a']
res = " ".join(x[::-1] for x in myList)
print(res)  # 87 97 a7
空气里的味道 2025-01-16 09:23:17

由于您尝试仅反转列表中的项目而不是列表本身,因此您只需要删除额外的 [::-1],因此您的代码应如下所示

myList = ['78', '79', '7a']
newList = [x[::-1] for x in myList]

:使用 reverseWord 方法的第二个代码是正确的,并且可以准确地为您提供所需的输出。

def reverseWord(word):
return word[::-1]

myList = ['78', '79', '7a']

newList = [reverseWord(word) for word in myList]

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:

myList = ['78', '79', '7a']
newList = [x[::-1] for x in myList]

In addition your second code using the reverseWord method is correct and gives you exactly the output you wanted.

def reverseWord(word):
return word[::-1]

myList = ['78', '79', '7a']

newList = [reverseWord(word) for word in myList]
疾风者 2025-01-16 09:23:17

好吧,一句话就能完成这项工作:

newList = list(map(lambda x:''.join(reversed(x)), myList))
['87', '97', 'a7']

Well, a one-liner to do the job :

newList = list(map(lambda x:''.join(reversed(x)), myList))
['87', '97', 'a7']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文