根据包含字符串的元素将列表拆分为子列表

Spliting a list into sublists based on an element containing a string

我知道有一个简单的解决方案,但我似乎找不到。

我想根据仅包含字符串的元素拆分列表。

在本例中为“商店”

from itertools import groupby

test_string = ['Store465', 'Steve', '145658', '125', 'Brad', '457958', '200', 'Store678', 'John', '30122', '898', '123', 'O', 'Joe', '36789', '123', 'U', ' 456']

# I've tried 

test_string[:] = [x for x in test_string if "Store" not in x]

print(test_string)

# but that will just remove the  Store elements

# ['Steve', '145658', '125', 'Brad', '457958', '200', 'John', '30122', '898', '123', 'O', 'Joe', '36789', '123', 'U', ' 456']

# and

test_result = [list(g) for k,g in groupby(test_string,lambda x:x if "Store" not in x) if not k]

# This creates an error. 
#
#   File "<input>", line 13
#     test_result = [list(g) for k,g in groupby(test_string,lambda x:x if "Store" not in x) if not k]
#                                                                                         ^
# SyntaxError: invalid syntax

我一直在使用 Whosebug 和 google 试图找到正确的语法或过程,但没有成功。我想要的输出是

[['Store465', 'Steve', '145658', '125', 'Brad', '457958', '200'], ['Store678', 'John', '30122', '898', '123', 'O', 'Joe', '36789', '123', 'U', ' 456']]

要根据 Store 在列表中出现的次数拆分列表,您可以这样做:

test_string = ['Store465', 'Steve', '145658', '125', 'Brad', '457958', '200', 'Store678', 'John', '30122', '898', '123', 'O', 'Joe', '36789', '123', 'U', ' 456']

test_loop = []
for item in test_string:
    if 'Store' in item: # create a new list to store all of the elements after store mentioned inside of the outer list
        test_loop.append([item])
    else:  # add elements after store into the last list and before the next mention of Store
        test_loop[-1].append(item)
print(test_loop)

给出:

[['Store465', 'Steve', '145658', '125', 'Brad', '457958', '200'], ['Store678', 'John', '30122', '898', '123', 'O', 'Joe', '36789', '123', 'U', ' 456']]