我有这个清单:[(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]
我想有效地迭代并实现项目+ 1 [0] - 项目[0]
如1 - 0,4 - 1,5 - 4
我目前有:
search_list = [(0, 'set'), (1, 'of'), (4, 'coloured')]
[search_list[i+1][0]-search_list[i][0] for i in range(0,len(search_list)-1)]
但我的代码效率不如我想的那么高。可以映射和lambda实现结果吗?
我想避免导入模块(但是,当然,如果lambda和map无法实现这一点)
答案 0 :(得分:0)
我不确定效率如何:
>>> search_list = [(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]
>>> [y[0]-x[0] for x,y in zip(search_list,search_list[1:])]
[1, 3, 1]
受欢迎的需求 itertools
版本:
>>> from itertools import izip, islice
>>> search_list = [(0, 'set'), (1, 'of'), (4, 'coloured'),(5, 'eels')]
>>> [y[0]-x[0] for x,y in izip(search_list, islice(search_list, 1, None))]
[1, 3, 1]