consecutive_numbers_in_a list & nested_loop & same_actions

1. detect consecutive nums in a list

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

2. if-elif-else in one line

tmp = 0 if a<100 else 1 if a > 100 else 3

3. nested-for-loop in a line

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实现

https://blog.sciencenet.cn/blog-1969089-1237137.html

全部精选博文导读

GMT+8, 2021-12-6 11:08