[英](In Python) What's the difference between list(string).reverse() and list(string)[::-1]?
I can execute both expressions in Python shell without error: 我可以在Python Shell中执行两个表达式而不会出现错误:
string = 'this is a string'
string ='这是一个字符串'
list(string)[::-1]列表(字符串)[::-1]
(output) ['g', 'n', 'i', 'r', 't', 's', ' ', 'a', ' ', 's', 'i', ' ', 's', 'i', 'h', 't']
(输出)['g','n','i','r','t','s',','a',',','s,'i','',' s”,“ i”,“ h”,“ t”]
list(string).reverse()
list(string).reverse()
I can do: 我可以:
string = ''.join(list(string)[::-1])
string =''.join(list(string)[::-1])
which effectively reverse the string in place. 有效地将字符串反转到位。 However when I do:
但是,当我这样做时:
string = ''.join(list(string).reverse()
string =''.join(list(string).reverse()
I got an error: 我收到一个错误:
TypeError: can only join an iterable
TypeError:只能加入可迭代
So list(string).reverse() does not return an iterable but list(string)[::-1] does. 因此list(string).reverse()不会返回可迭代,而list(string)[::-1]会返回。 Can someone help me understand the underlying differences?
有人可以帮助我了解潜在差异吗?
list(string).reverse()
modifies the list in place and returns None
list(string).reverse()
修改列表并返回None
So you are are doing: 所以你正在做:
"".join(None)
Hence the error. 因此,错误。
list.reverse()
更改了从其调用的列表,因此在调用后会更改列表,而sequence[::-1]
创建一个新列表并返回它,因此原始列表不受影响。
list.reverse
is returning None
so you don't need to assign it back, but, seq[::-1]
needs to be assigned back, Example: list.reverse
返回None
因此您无需将其分配回去,但是需要将seq[::-1]
分配回去,例如:
l=[1,2,3]
print(l.reverse())
print(l)
Output: 输出:
None
[3,2,1]
Example 2: 范例2:
l=['a','b','c']
print(l[::-1])
print(l)
Output: 输出:
['c','b','a']
['a','b','c']
Example 2 needs to be assigned back 示例2需要分配回去
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.