||
def detect_consecutive_nums(num_list):
''' group consecutive numbers
Example: num_list = [3,4,5,7,10,11,1]
nums_grouped = [[3, 4, 5], [7], [10, 11], [1]]'''
from itertools import groupby
from operator import itemgetter
nums_grouped = []
key_func = lambda ix: ix[0]-ix[1]
for k, g in groupby(enumerate(num_list), key_func):
nums_grouped.append(list(map(itemgetter(1), g)))
return nums_grouped
refer to: https://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list
tmp = 0 if a<100 else 1 if a > 100 else 3
2.1 two-for-loops in one line
[(x,y) for x in [1,2,3] for y in [3,1,4]]
<==> combs = [] for x in [1,2,3]: for y in [3,1,4]: if x!=y: combs.append((x,y))
以上代码中,combs为[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
2.2 [[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
4. do the same actions for two lists
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
C = [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
itertools.product: returns an iterable yielding tuples of values from all the iterables you pass it.
That is, itertools.product(A, B) yields all values of the form (a, b), where the a values come from A and the b values come from B.
#此方法也可用zip实现
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-23 01:35
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社