写个函数,把list1变成res,最好像Python的风格

list1=[["a1","a2"],["b1","b2"],["c1","c2"],["d1","d2"]]

res=[["a1", "a2"], ["a2", "b1"], ["b1", "b2"], ["b2", "c1"], ["c1", "c2"], ["c2", "d1"], ["d1", "d2"]]

代码如下:

>>> list1 = [["a1","a2"],["b1","b2"],["c1","c2"],["d1","d2"]]
# 方法一:使用lambda表达式
>>> from functools import reduce
>>> l = list(reduce(lambda x,y:x+y,list1))
>>> l
['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2']
>>> res = [l[i:i+2] for i in range(len(l)-1)]
>>> res
[['a1', 'a2'], ['a2', 'b1'], ['b1', 'b2'], ['b2', 'c1'], ['c1', 'c2'], ['c2', 'd1'], ['d1', 'd2']]
>>> l = []
>>> l
[]
# 方法二:使用sum()函数
>>> l = sum(list1, [])
>>> l
['a1', 'a2', 'b1', 'b2', 'c1', 'c2', 'd1', 'd2']
>>> res = [l[i:i+2] for i in range(len(l)-1)]
>>> res
[['a1', 'a2'], ['a2', 'b1'], ['b1', 'b2'], ['b2', 'c1'], ['c1', 'c2'], ['c2', 'd1'], ['d1', 'd2']]
>>> 

 

posted on 2013-04-22 21:12  101010  阅读(1737)  评论(0编辑  收藏  举报