简体   繁体   中英

Is there a str.split equivalent for lists in Python?

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?

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))

import itertools.groupby ,然后:

list(list(g) for k,g in groupby(inputList, lambda x: x!=None) if k)

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
# Practicality beats purity
final = []
row = []
for el in the_list:
    if el is None:
        if row:
            final.append(row)
        row = []
        continue
    row.append(el)
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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM