Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(在Python中)什么';s list(string).reverse()和list(string)[::-1]之间的区别是什么?_Python_List_Iterable - Fatal编程技术网

(在Python中)什么';s list(string).reverse()和list(string)[::-1]之间的区别是什么?

(在Python中)什么';s list(string).reverse()和list(string)[::-1]之间的区别是什么?,python,list,iterable,Python,List,Iterable,我可以在Python shell中执行这两个表达式而不会出错: string='这是一个字符串' 列表(字符串)[::-1] (输出)['g','n','i','r','t','s','a','s','i','s','i','h','t'] 列表(字符串).reverse() 我可以做到: string=''.join(列表(字符串)[::-1]) 这有效地扭转了弦的位置。然而,当我这样做时: string=''.join(list(string).reverse() 我有一个错误: TypeE

我可以在Python shell中执行这两个表达式而不会出错:

string='这是一个字符串'
列表(字符串)[::-1]

(输出)['g','n','i','r','t','s','a','s','i','s','i','h','t']

列表(字符串).reverse()

我可以做到:

string=''.join(列表(字符串)[::-1])

这有效地扭转了弦的位置。然而,当我这样做时:

string=''.join(list(string).reverse()

我有一个错误:

TypeError:只能加入一个iterable

因此,list(string).reverse()不返回iterable,但list(string)[::-1]返回。有人能帮我理解基本的区别吗?

list.reverse()
变异它从中调用的列表,以便在调用后更改列表,而
序列[:-1]
创建一个新列表并返回它,因此原始列表不受影响。

列表(字符串)。reverse()
就地修改列表并返回
None

所以你正在做:

"".join(None)

因此出现错误。

list.reverse
返回
None
,因此您不需要重新分配它,但是,
seq[::-1]
需要重新分配,例如:

l=[1,2,3]
print(l.reverse())
print(l)
输出:

None
[3,2,1]
['c','b','a']
['a','b','c']
例2:

l=['a','b','c']
print(l[::-1])
print(l)
输出:

None
[3,2,1]
['c','b','a']
['a','b','c']

示例2需要重新分配

值得注意的是,字符串可以直接切片,您不需要先创建列表,然后将字母重新连接在一起。只需使用
string[:-1]