>>> a =list()>>> a
[]>>> b =list((3.14,False,'x',None))>>> b
[3.14,False,'x',None]>>> c =list({1,2,3})>>> c
[1,2,3]>>> d =list({'x':1,'y':2,'z':3})>>> d
['x','y','z']>>> e =list(range(5))>>> e
[0,1,2,3,4]>>> f =list('*'*i for i inrange(5))>>> f
['','*','**','***','****']
>>> a =[3.14,False,'x',None]>>>
a[2:2]=[1,2,3]>>> a
[3.14,False,1,2,3,'x',None]
1
2
3
4
1.3 列表的方法
对于列表对象的方法如果能信手拈来,那就是Python高手了。
>>> a =[3.14,False,'x',None]>>> a.index('x')2>>> a.append([1,2,3])>>> a
[3.14,False,'x',None,[1,2,3]]>>> a[-1].insert(1,'ok')>>> a
[3.14,False,'x',None,[1,'ok',2,3]]>>> a.remove(False)>>> a
[3.14,'x',None,[1,'ok',2,3]]>>> a.pop(1)'x'>>> a
[3.14,None,[1,'ok',2,3]]>>> a.pop()[1,'ok',2,3]>>> a
[3.14,None]
>>> a =dict()>>> a.update({'name':'xufive','gender':'男'})>>>list(a.keys())['name','gender']>>>list(a.values())['xufive','男']>>>list(a.items())[('name','xufive'),('gender','男')]
>>> a =(3,4)>>> a[0]=5
Traceback (most recent call last):
File "<pyshell#14>", line 1,in<module>
a[0]=5
TypeError:'tuple'object does not support item assignment
1
2
3
4
5
6
3.2 必入之深坑
使用了多年Python之后,我曾经写出的最糟糕的bug,就是下面这一段代码。
>>>import threading
>>>defdo_something(name):print('My name is %s.'%name)>>> th = threading.Thread(target=do_something, args=('xufive'))>>> th.start()
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926,in _bootstrap_inner
self.run()
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870,in run
self._target(*self._args,**self._kwargs)
TypeError: do_something() takes 1 positional argument but 6 were given
>>> a =(5)>>> a
5>>>type(a)<class'int'>>>> b =('xyz')>>> b
'xyz'>>>type(b)<class'str'>>>> a, b =(5,),('xyz',)>>> a, b
((5,),('xyz',))>>>type(a),type(b)(<class'tuple'>,<class'tuple'>)
>>> s ={1,'x',(3,4,5)}>>> s
{1,(3,4,5),'x'}>>> s ={1,'x',[3,4,5]}
Traceback (most recent call last):
File "<pyshell#32>", line 1,in<module>
s ={1,'x',[3,4,5]}
TypeError: unhashable type:'list'