本文主要探讨一下在 Python 各种创建 list, set, tuple 和 dictionary 的方式。首先看
最常用的创建方式
1 2 3 4 |
alist = [1, 2] # type(alist) <class 'list'> aset = {1, 2} # type(aset) <class 'set'> atuple = (1, 2) # type(atuple) <class 'tuple'> adict = {'k1': 1, 'k2': 2} # type(adict) <class 'dict'> |
以上相当于是针对右边的值调用了相应的构造函数,如 list([1, 2]), set({1, 2}), tupe((1, 2)), dict({'k1': 1, 'k2': 2})
创建 set 和 dictionary 都是用大括号 {}
, 对于 tuple 如果是单个元素时,要附加一个逗号
1 |
atuple = (1,) |
如果省略逗号,会怎样呢? 阅读全文 >>