python列表反向查询_Python反向列表

在Python中,反转字符串或列表有多种方法。例如,使用`[::-1]`切片可以方便地反转字符串,而使用`reverse()`方法可以就地反转列表。在涉及列表时,要注意`reverse()`不会返回新列表,而是直接修改原列表。此外,通过`' '.join()`和`[::-1]`结合可以实现单词顺序的反转。
摘要由CSDN通过智能技术生成

Python反向列表

这个问题已经在这里有了答案:

反转Python中的字符串 26个答案

我正在尝试反转一个字符串,并使用下面的代码,但是生成的反转列表值为None。

代码:

str_a = 'This is stirng'

rev_word = str_a.split()

rev_word = rev_word.reverse()

rev_word = ''.join(rev_word)

它返回TypeError。为什么?

user1050619 asked 2020-06-25T21:45:17Z

8个解决方案

119 votes

这是我个人最喜欢的反转字符串的方法:

stra="This is a string"

revword = stra[::-1]

print(revword) #"gnirts a si sihT

或者,如果您想颠倒单词顺序:

revword = " ".join(stra.split()[::-1])

print(revword) #"string a is This"

:)

Sean Johnson answered 2020-06-25T21:46:13Z

51 votes

stringaisThis返回stringaisThis。因此,不应将其分配给变量。

使用此代替:

stra = 'This is a string'

revword = stra.split()

revword.reverse()

revword=''.join(revword)

我已经为您在IDEOne上运行了代码,因此您可以看到输出。 (还请注意,输出为293909689832361212672;您可能要使用293909689832361212673,并带有空格。)

还要注意,您提供的方法仅使单词反向,而不使文本反向。 @ ron.rothman提供了一个链接,该链接详细说明了如何完全反转字符串。

Eric answered 2020-06-25T21:45:45Z

7 votes

字符串上的各种反转:

instring = 'This is a string'

reversedstring = instring[::-1]

print reversedstring # gnirts a si sihT

wordsreversed = ' '.join(word[::-1] for word in instring.split())

print wordsreversed # sihT si a gnirts

revwordorder = ' '.join(word for word in instring.split()[::-1])

print revwordorder # string a is This

revwordandorder = ' '.join(word[::-1] for word in instring.split()[::-1])

print revwordandorder # gnirts a si sihT

Paddy3118 answered 2020-06-25T21:46:33Z

6 votes

供将来参考,当对象具有类似sorted的方法时,通常对对象执行该操作(即,列表已排序且不返回任何内容,无),而内置函数如sorted则对对象执行操作并返回 值(即排序列表)

dm03514 answered 2020-06-25T21:46:53Z

3 votes

>>> s = 'this is a string'

>>> s[::-1]

'gnirts a si siht'

>>> ''.join(reversed(s))

'gnirts a si siht'

Andreas Jung answered 2020-06-25T21:47:09Z

0 votes

for循环从结尾(最后一个字母)到开始(第一个字母)迭代字符串

>>> s = 'You can try this too :]'

>>> rev = ''

>>> for i in range(len(s) - 1, -1, -1):

... rev += s[i]

>>> rev

']: oot siht yrt nac uoY'

Aziz Alto answered 2020-06-25T21:47:29Z

0 votes

根据评论和其他答案:

str_a = 'this is a string'

rev_word = ' '.join(reversed(str_a.split()))

方法链接毕竟在Python中有效...

answered 2020-06-25T21:47:53Z

0 votes

反向列表可以使用多种方法来完成。

如前面的答案中所述,两个非常突出,一个具有reverse()功能,两个具有切片功能。 我提供了一些我们应该选择哪种见解。我们应该始终使用reverse()函数来反转Python列表。 有两个原因,一个是就地逆转,另一个是比其他更快。我有一些数字可以支持我的回答,

In [15]: len(l)

Out[15]: 1000

In [16]: %timeit -n1 l.reverse()

1 loops, best of 3: 7.87 µs per loop

In [17]: %timeit -n1 l[::-1]

1 loops, best of 3: 10 µs per loop

对于1000个整数列表,与切片相比,reverse()函数的性能更好。

Aashish P answered 2020-06-25T21:48:22Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值