1 一行赋值序列和元组
In [11]: l = [‘a‘, ‘b‘] In [12]: x,y = l In [13]: x Out[13]: ‘a‘ In [14]: y Out[14]: ‘b‘
In [15]: t = (1,2) In [16]: m,n =t In [17]: m Out[17]: 1 In [18]: n Out[18]: 2
2 交换变量
In [6]: m = 3 In [7]: n = 4 In [8]: m,n = n,m In [9]: m Out[9]: 4 In [10]: n Out[10]: 3
3 语句在行内,if 的三目运算
In [19]: print ‘Hello‘ if True else ‘World‘ Hello
In [20]: a = ‘ ni‘ In [21]: b = a.strip() if a.strip() else None In [22]: b Out[22]: ‘ni‘ In [23]: a = ‘ ‘ In [24]: b = a.strip() if a.strip() else None In [25]: b
4 连接--相同类型的数据可以连接拼接
In [27]: s = ‘my name is: ‘ In [28]: msg = s + ‘Andy‘ In [29]: msg Out[29]: ‘my name is: Andy‘
In [30]: l1 = [‘Apple‘, ‘orange‘] In [31]: l2 = [‘Banana‘, ‘Grape‘] In [32]: l1 + l2 Out[32]: [‘Apple‘, ‘orange‘, ‘Banana‘, ‘Grape‘]
5 数字技巧
整数和浮点除
In [33]: 5 /2 Out[33]: 2 In [34]: 5.0 /2 Out[34]: 2.5
整数和浮点取余数
In [36]: 5 %2 Out[36]: 1 In [37]: 5.00 %2 Out[37]: 1.0
6 数字比较和少语言可以如此用法
In [43]: if x < 5 and x >2: ....: print x ....: 3
等于
In [44]: if 2 < x < 5: ....: print x ....: 3
7 同时迭代两个列表(序列)
In [46]: l1 Out[46]: [‘Apple‘, ‘orange‘] In [47]: l2 Out[47]: [‘Banana‘, ‘Grape‘] In [48]: for item1, item2 in zip(l1, l2): ....: print item1 + ‘ vs ‘ + item2 ....: Apple vs Banana orange vs Grape
8 带索引的列表迭代
In [51]: for index, item in enumerate(l1): ....: print index, item ....: 0 Apple 1 orange
In [52]: for index, item in enumerate(l1): ....: print index +1, item ....: 1 Apple 2 orange
9 生成列表(列表推到式)
In [53]: numbers = [1,2,3,4,5,6,7,8] In [54]: even = [] In [55]: for number in numbers: ....: if number%2 == 0: ....: even.append(number) ....: In [56]: even Out[56]: [2, 4, 6, 8]
等价于一行语句
In [59]: even = [ number for number in numbers if number %2 == 0] In [60]: even Out[60]: [2, 4, 6, 8]
10 字典推导(只使用 python 2.7版本 不适合以下版本)
names = [‘andy‘, ‘jack‘, ‘tom‘, ‘john‘] d = {key: value for value, key in enumerate(names)}
11 列表转字符串
In [64]: l1 Out[64]: [‘Apple‘, ‘orange‘] In [66]: ",".join(l1) Out[66]: ‘Apple,orange‘
12 字符串转列表
In [67]: ids = "4,57,9,22,31" In [68]: ids.split(‘,‘) Out[68]: [‘4‘, ‘57‘, ‘9‘, ‘22‘, ‘31‘]
时间: 2024-10-14 15:57:57