gll89的个人博客分享 http://blog.sciencenet.cn/u/gll89

博文

consecutive_numbers_in_a list & nested_loop & same_actions

已有 1931 次阅读 2020-6-9 15:05 |个人分类:Python|系统分类:科研笔记

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://blog.sciencenet.cn/blog-1969089-1237137.html

上一篇:[转载]EfficientNet启示
下一篇:brain viewers
收藏 IP: 221.12.54.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 19:01

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部