# 直到现在才想明白：Python的精髓居然是花括号、圆括号、方括号！

·  阅读 90

1. 方括号

``````        a = []>>> a[]>>> b = [3.14, False, 'x', None]>>> b[3.14, False, 'x', None]123456

``````        c = [i**2 for i in range(5)]>>> c[0, 1, 4, 9, 16]123

``````        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['', '', '', '**', '****']123456789101112131415161718

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]12345678910111213

``````        a = [3.14, False, 'x', None]>>> a[2:2] = [1,2,3]>>> a[3.14, False, 1, 2, 3, 'x', None]1234

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]1234567891011121314151617181920

1. 花括号

``````        a = {}>>> a{}>>> b = {'x','y','z'}>>> b{'y', 'z', 'x'}>>> type(a)<class 'dict'>>>> type(b)<class 'set'>12345678910

``````        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}12345678910111213141516

Py2时代，dict对象曾经有has_key()的方法，用来判断是否包含某个键。py3舍弃了这个方法,判断一个键是否存在于字典中，只能使用in这样的方法了。

``````        a = dict({'x':1, 'y':2, 'z':3})>>> 'x' in aTrue>>> 'v' in aFalse12345

2.2 向字典中添加一个新键或更新键值

``````        a = dict()>>> a['name'] = 'xufive'>>> a{'name': 'xufive'}1234

``````        a = dict()>>> a.update({'name':'xufive', 'gender':'男'})>>> a{'name': 'xufive', 'gender': '男'}1234

2.3 从字典中获取一个键值

a[‘age’]是最常用的方式，但是也还会遇到键不存在的异常。下面的方法值得推荐。

``````        a.get('age', 18)1812

2.4 获取字典的全部键、全部值、全部键值对

dict类提供了keys()、values()和items()等三个方法分别返回字典的全部键、全部值和全部键值对。需要注意的是，返回结果并非列表，而是迭代器。如果你需要列表形式的返回结果，请使用list()转换。

``````        a = dict()>>> a.update({'name':'xufive', 'gender':'男'})>>> list(a.keys())['name', 'gender']>>> list(a.values())['xufive', '男']>>> list(a.items())[('name', 'xufive'), ('gender', '男')]12345678

2.5 遍历字典

``````        a = dict([('name', 'xufive'), ('gender', '男')])>>> for key in a: print(key, a[key]) name xufivegender 男123456

1. 圆括号

``````        a = (3, 4)>>> a[0] = 5Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> a[0] = 5TypeError: 'tuple' object does not support item assignment123456

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 given12345678910111213

``````        a = (5)>>> a5>>> 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'>)123456789101112131415

3.3 单星号解包元组

``````        args = (95,99,100)>>> '%s：语文%d分，数学%d分，英语%d分'%('天元浪子', args[0], args[1], args[2])'天元浪子：语文95分，数学99分，英语100分'123

``````        args = (95,99,100)>>> '%s：语文%d分，数学%d分，英语%d分'%('天元浪子', *args)'天元浪子：语文95分，数学99分，英语100分'123

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'12345678