先贴上代码在分析
#3 有多少个2012年11月发布的tweets
lines_from_2012_11 = filter(lambda line: line[keys['created_at']].startswith('2012-11'), lines)
lines_total_from_2012_11 = len(lines_from_2012_11)
assert type(lines_total_from_2012_11) == int
第一个是filter
# coding=utf-8
import math
# python 内置函数filter用于过滤序列
# 例如,在一个list中删除偶数
def is_odd (n):
return n % 2 != 0
filter(is_odd, range(0, 10))
# 找出1-100内的素数
def is_primer_num(n):
if n == 1:
return False
else:
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
filter(is_primer_num, range(1, 100))
第二个是lambda
# coding=utf-8
# lambda表达式通常是在需要一个函数但是又不想费神去写一个函数时使用,也就是匿名函数
# 看一个例子,将0-10内的每个数平方
map(lambda x: x*x, [y for y in range(0, 10)])
# 这样的写法好过
def sq(x):
return x*x
map(sq, [y for y in range(0, 10)])
# 匿名函数本质上也是一个函数
a = [1, 2, 3]
r = map(lambda x: x+1, a)
# map(f, a)也就是将f依次套用在a的每个元素上。
# coding=utf-8
# python starstwith() 方法用于检查字符串是否以指定字符串开头,同时也可以指定查找的范围
# str.startswith(str, beg=0,end=len(string));
str = 'abcdefg'
print str.startswith('ab')
print str.startswith('bc', 1, 4)
print str.startswith('ab', 1, 4)
True
True
False
<pre name="code" class="python">#5 该文本里,在哪个小时发布的数据最多?
# todo 这里用time模块做时间转换最好。下例只为讲解拆分方法
hours = [int(line[keys['created_at']][11:13]) for line in lines]
total_by_hour = [(h, hours.count(h)) for h in xrange(0, 24)]
total_by_hour.sort(key=lambda k: k[1], reverse=True)
max_hour = total_by_hour[0][0]
assert type(max_hour) == int
# coding=utf-8
# 先生成了一个list,这个list包含了24个元祖
A = [(1, 2), (3, 4), (5, 6)]
print type(A)
print type(A[0])
print A[0][1]
<type 'list'>
<type 'tuple'>
2
在sort中加入了一个函数,key=lambda k : k[1],因为k对应的是一个tuple,它的k[1]代表了它的出现次数,按照这个来进行一个逆序排序
total_by_hour.sort(key=lambda k: k[1], reverse=True)