1. 访问数组下标和成员
二逼程序员写法:
arr = [1,2,3,4,5,6]
i = 0
for item in arr:
print i, item
i += 1
文艺程序员写法:
arr = [1,2,3,4,5,6]
for i, item in enumerate(arr):
print i, item
2. 初始化
二逼程序员做法:
arr = []
for i in range(100):
if i%2 == 0:
arr.append(i)
文艺程序员做法:
arr = [ i for i in range(100) if i%2==0]
3. 去重
二逼程序员做法:
arr = [1,1,2,2,3,3]
arr2= []
for x in arr:
if x not in arr2:
arr2.append(x)
文艺程序员做法:
arr = [1,1,2,2,3,3]
arr2 = list(set(arr))
4. 数组访问
二逼程序员做法:
arr = [1,2,3,4,5,6,7,8]
i = 0
while i < len(arr):
print arr[i]
i += 2
文艺程序员做法:
arr = [1,2,3,4,5,6,7,8]
for i in range(0, len(arr), 2):
print arr[i]
5. 条件赋值
普通程序员做法:
x = 1
if x >1:
y += 1
else:
y -= 1
文艺程序员做法:
x = 1
y = x+1 if x>1 else: x-1
6. 字符串连接
二逼程序员做法:
arr = ['a', 'b', 'c']
result = ''
for i in arr:
result += i
文艺程序员做法:
arr = ['a', 'b', 'c']
result = ''.join(arr)
7. 条件判断
普通程序员做法:
a = 5
if a > 2 and a < 10:
print 'yeah!'
else:
print 'oooh!'
文艺程序员做法:
a = 5
if 2<a<10:
print 'yeah!'
else:
print 'oooh!'
8. 字典操作
普通程序员做法:
dict1 = {'age':18}
if dict1.has_key('age'):
dict1['age'] += 1
else:
dict1['age'] = 1
文艺程序员做法:
dict1 = {'age':18}
dict1['age'] = dict1['age']+1 if 'age' in dict1 else 1
记住
in
比has_key
更 pythonic!
9. 打印100个'*'
二逼程序员做法:
a = ''
for i in range(100):
a += '*'
print a
文艺程序员做法:
print '*'*100
10. 字符串反转
二逼程序员做法:
def reverse(s):
rt = ''
for i in range(len(s)-1, -1, -1):
rt += s[i]
return rt
文艺程序员做法:
def reverse(s):
return s[::-1]
神经病程序员做法:
from functools import reduce
def reverse (s):
return reduce(lambda x,y:y+x,s)
不知道
reduce
是干啥的? 嗯嗯,后面会有讲。