5

If I have a string, I can split it up around whitespace with the str.split method:

"hello world!".split()

returns

['hello', 'world!']

If I have a list like

['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]

Is there a split method that will split around None and give me

[['hey', 1], [2.0, 'string', 'another string'], [3.0]]

If there is no built-in method, what would be the most Pythonic/elegant way to do it?

4

5 回答 5

8

A concise solution can be produced using itertools:

groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
    if k:
        groups.append(list(g))
于 2012-08-19T02:42:02.443 回答
3

import itertools.groupby, then:

list(list(g) for k,g in groupby(inputList, lambda x: x!=None) if k)
于 2012-08-19T03:06:26.397 回答
1

There is not a built-in way to do this. Here's one possible implementation:

def split_list_by_none(a_list):
    result = []
    current_set = []
    for item in a_list:
        if item is None:
            result.append(current_set)
            current_set = []
        else:
            current_set.append(item)
    result.append(current_set)
    return result
于 2012-08-19T02:37:40.850 回答
1
# Practicality beats purity
final = []
row = []
for el in the_list:
    if el is None:
        if row:
            final.append(row)
        row = []
        continue
    row.append(el)
于 2012-08-19T02:38:04.377 回答
0
def splitNone(toSplit:[]):
    try:
        first = toSplit.index(None)
        yield toSplit[:first]
        for x in splitNone(toSplit[first+1:]):
            yield x
    except ValueError:
        yield toSplit

 

>>> list(splitNone(['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]))
[['hey', 1], [2.0, 'string', 'another string'], [3.0]]
于 2012-08-19T03:03:18.660 回答