混淆列表括号和括号&分配前的操作员

时间:2014-02-11 05:37:26

标签: python python-2.7 python-3.x

很少有事情让我感到困惑,首先是在列表中有什么区别

list1 = [100,200,300] 和, list3 = [(1,1),(2,4),(3,)]

当然,我明显看到了视觉上的差异,但我没有看到括号旁边的区别。

还有什么意思?它实际上做了什么? 当我们使用这样的运算符时 list + = 1 要么 list - = 1 完全糊涂了。 搜索了很多,但似乎我在寻找错误的内容。 非常感谢提前。

3 个答案:

答案 0 :(得分:1)

>>> list1 = [100,200,300]
>>> list3 = [(1,1), (2,4), (3,)]

>>> for item in list1:
...     print("{}: {}".format(repr(item), type(item)))
... 
100: <type 'int'>
200: <type 'int'>
300: <type 'int'>

>>> for item in list3:
...     print("{}: {}".format(repr(item), type(item)))
... 
(1, 1): <type 'tuple'>
(2, 4): <type 'tuple'>
(3,): <type 'tuple'>

list += 1

list -= 1

会导致异常 - 例如。

>>> list += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'type' and 'int'

除非有人用自己的变量

遮蔽了内置函数
>>> list = 999
>>> list += 1
>>> list
1000

答案 1 :(得分:1)

这是三个数字的列表:

list1 = [100,200,300]

这是三个tuples的列表:

list3 = [(1,1), (2,4), (3,)]

元组是一个不可变的(不能在不破坏和创建新元素的情况下进行更改)按键索引的有序项集合。

除了引发错误之外,这不会执行任何操作,因为您无法在列表中添加数字:

>>> i = [1,2,3]
>>> i += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

如果您使用可以一起添加的两种类型,那么+=会将右侧的值添加到左侧名称所指向的值:

>>> i = 1
>>> i += 1
>>> i
2

与此相同:

>>> i = 1
>>> i = i + 1
>>> i
2

答案 2 :(得分:1)

 list1=[100,200,300] ==> is a list and element in this list is mutable means you can change the value of element by accessing any index in list, ex: list1[1]=400

 list3 = [(1,1), (2,4), (3,)] ==> is a list of tubles; tuples in python represented by (). This indicates elements in tuples can't be changed. In list3, you access each tuples by using it's index; for ex list3[0] returns (1,1) which is list element. list3[0][0] returns 1 which is tuple element. The difference here is that you cannot assign like list3[0][0] = 2.

您可以在python documentation了解详情!