Python';不可变列表的奇怪行为
为什么python会这样对待字符串列表Python';不可变列表的奇怪行为,python,tuples,Python,Tuples,为什么python会这样对待字符串列表 $ python Python 2.6.6 (r266:84292, May 27 2013, 05:35:12) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = ('sim') >>> x[0] 's' 当可变列
$ python
Python 2.6.6 (r266:84292, May 27 2013, 05:35:12)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = ('sim')
>>> x[0]
's'
当可变列表执行此操作时
$ python
Python 2.6.6 (r266:84292, May 27 2013, 05:35:12)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = ['sim']
>>> x[0]
'sim'
这里没有一个不变的
列表。你认为你拥有的东西叫做元组,但它不是。括号仅用于分组。你真的只有一个普通的字符串。如果要指示元组,请使用逗号:
>>> x = ('sim')
>>> x
'sim'
>>> type(x)
<class 'str'>
>>> x = ('sim',)
>>> x[0]
'sim'
>>> type(x)
<class 'tuple'>
>x=('sim')
>>>x
“sim”
>>>类型(x)
>>>x=('sim',)
>>>x[0]
“sim”
>>>类型(x)
那里没有一个不变的列表。你认为你拥有的东西叫做元组,但它不是。括号仅用于分组。你真的只有一个普通的字符串。如果要指示元组,请使用逗号:
>>> x = ('sim')
>>> x
'sim'
>>> type(x)
<class 'str'>
>>> x = ('sim',)
>>> x[0]
'sim'
>>> type(x)
<class 'tuple'>
>x=('sim')
>>>x
“sim”
>>>类型(x)
>>>x=('sim',)
>>>x[0]
“sim”
>>>类型(x)
其他答案(正确答案)的快速版本:
必须在括号中使用逗号“,”使其成为元组
如果没有逗号,您只有一个字符串,实际上该字符串的第一个索引是“s”。对于其他答案的快速版本(正确):
您必须在括号中使用逗号“”,使其成为元组
如果没有逗号,您只有一个字符串,实际上该字符串的第一个索引是“s”