高琳琳
consecutive_numbers_in_a list & nested_loop & same_actions
2020-6-9 15:05
阅读:2004

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


refer to: https://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list


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://wap.sciencenet.cn/blog-1969089-1237137.html?mobile=1

收藏

分享到:

当前推荐数:0
推荐到博客首页
网友评论0 条评论
确定删除指定的回复吗?
确定删除本博文吗?