Take sequence of values from a python list

北城余情 提交于 2019-12-06 13:38:59

问题


I have a array like this,

a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]

and I want to make list of values that are lesser than 7 (look like following)

b = [[3,2,5],[4,5,6,3],[4,5],[5],[4],[6]]

So I used following method,

>>> from itertools import takewhile
>>> a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]
>>>list(takewhile(lambda x: x < 7 , a))
[3, 2, 5]

But I only get the first sequence. Can anyone help me to solve this problem ? Thank you.


回答1:


a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]
from itertools import groupby
[list(g) for k, g in groupby(a, lambda x:x<7) if k]

Output:

[[3, 2, 5], [4, 5, 6, 3], [4, 5], [5], [4], [6]]



回答2:


that because takewhile return elements as long as the condition is True, if not it just do break , and leave the function.

you will need something like this :

big_list = [].
small_list = []
for number in a:
    if number <7 :
        small_list.append(number)
    else:
        if small_list: # this is for not appending empty lists
            big_list.append(small_list)
        small_list = []


来源:https://stackoverflow.com/questions/46752146/take-sequence-of-values-from-a-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!