用了十几年才想明白:Python的精髓居然是方括号、花括号和圆括号!
作者:天元浪子
来源:Python作业辅导员
1. 方括号
1.1 创建列表
>>> a = []
>>> a
[]
>>> b = [3.14, False, 'x', None]
>>> b
[3.14, False, 'x', None]
>>> c = [i**2 for i in range(5)]>>> c[0, 1, 4, 9, 16]
>>> 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 in range(5))
>>> f
['', '*', '**', '***', '****']
1.2 列表的索引
>>> [3.14, False, 'x', None][2]'x'>>> [3.14, False, 'x', None][-2]'x'>>> [3.14, False, 'x', None][1:][False, 'x', None]>>> [3.14, False, 'x', None][:-1][3.14, False, 'x']>>> [3.14, False, 'x', None][::2][3.14, 'x']>>> [3.14, False, 'x', None][::-1][None, 'x', False, 3.14]
>>> a = [3.14, False, 'x', None]
>>> a[2:2] = [1,2,3]
>>> a
[3.14, False, 1, 2, 3, 'x', None]
1.3 列表的方法
>>> 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]
2. 花括号
>>> a = {}
>>> a
{}
>>> b = {'x','y','z'}
>>> b
{'y', 'z', 'x'}
>>> type(a)
<class 'dict'>
>>> type(b)
<class 'set'>
>>> dict(){}>>> dict({'x':1, 'y':2, 'z':3}){'x': 1, 'y': 2, 'z': 3}>>> dict((('x',1), ('y',2), ('z',3))){'x': 1, 'y': 2, 'z': 3}>>> dict.fromkeys('xyz'){'x': None, 'y': None, 'z': None}>>> dict.fromkeys('abc', 0){'a': 0, 'b': 0, 'c': 0}>>> set((3,4,5)){3, 4, 5}>>> set({'x':1, 'y':2, 'z':3}){'y', 'z', 'x'}>>> set([3,3,4,4,5,5]){3, 4, 5}
2.1 判断一个键是否存在于字典中
>>> a = dict({'x':1, 'y':2, 'z':3})
>>> 'x' in a
True
>>> 'v' in a
False
2.2 向字典中添加一个新键或更新键值
>>> a = dict()>>> a['name'] = 'xufive'>>> a{'name': 'xufive'}
>>> a = dict()
>>> a.update({'name':'xufive', 'gender':'男'})
>>> a
{'name': 'xufive', 'gender': '男'}
2.3 从字典中获取一个键值
>>> a.get('age', 18)18
2.4 获取字典的全部键、全部值、全部键值对
>>> a = dict()
>>> a.update({'name':'xufive', 'gender':'男'})
>>> list(a.keys())
['name', 'gender']
>>> list(a.values())
['xufive', '男']
>>> list(a.items())
[('name', 'xufive'), ('gender', '男')]
2.5 遍历字典
>>> a = dict([('name', 'xufive'), ('gender', '男')])>>> for key in a: print(key, a[key])
name xufivegender 男
3. 圆括号
3.1 必入之浅坑
>>> 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
3.2 必入之深坑
>>> import threading>>> def do_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'>)
3.3 单星号解包元组
>>> args = (95,99,100)>>> '%s:语文%d分,数学%d分,英语%d分'%('天元浪子', args[0], args[1], args[2])'天元浪子:语文95分,数学99分,英语100分'
>>> args = (95,99,100)
>>> '%s:语文%d分,数学%d分,英语%d分'%('天元浪子', *args)
'天元浪子:语文95分,数学99分,英语100分'
3.4 为什么要使用元组?
>>> 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'
赞 (0)