我知道有一个简单的解决方案,但我似乎找不到。
我想根据只包含字符串的元素来拆分列表。
在这种情况下;存储";
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
我一直在stackoverflow和谷歌上试图找到正确的语法或过程,但没有成功。我想要的输出是
[['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']]