记录几个python语法的小技巧。
1. 变换变量
x = 5
y = 6
x, y = y, x
print x,y
2. 行内if语句
print 'Python' if True else 'Objective-C'
3.连接
l1 = ['python','objective-c']
l2 = ['swift']
l3 = l1 + l2
print l3
4.向下取整
print 5.0//2
print 2**5
5.浮点数的除法
print .3/.1
print .3//.1
6.数值比较
x = 2
if 3 > x < 1:
print x
if 1 < x > 0:
print x
7.两个列表同时迭代
l1 = ['python','objective-c']
l2 = ['swift','javascript']
#zip把两个列表组合成一个列表,但是新的列表里面每一个值都是一个tuple
for item1,item2 in zip(l1,l2):
print item1,item2
8.带索引的迭代
l1 = ['python','objective-c','swift','javascript']
for index,language in enumerate(l1):
print language + ' index is ' + str(index)
9.列表推导
nums = [x for x in range(11)]
print nums
nums2 = [x for x in nums if x%2 == 0]
print nums2
10.索引推导
dict = {'name':'shuige','age':'20'}
print {key:value for value,key in enumerate(dict)}
11.初始化列表
items = [0]*3
print items
12.列表转换成字符串
l1 = ['python','objective-c','swift','javascript']
print ','.join(l1)
13.字典取元素
dict = {'name':'shuige','age':'20'}
#如果有值,打印,没有的话,会打印True
name = dict.get('name',True)
print name
14.切片
x = [x for x in range(11)]
print x[:3]
print x[1::2] #从索引1开始每隔两个
print x[1::3]