简体   繁体   English

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

[英]Spliting a list into sublists based on an element containing a string

I know there is a simple solution but I can't seem to find it.我知道有一个简单的解决方案,但我似乎找不到。

I want to split a list based on an element just containing a string.我想根据仅包含字符串的元素拆分列表。

In this case "Store"在这种情况下,“商店”

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

I've been on stackoverflow and google trying to find the correct syntax or process with no luck.我一直在使用 stackoverflow 和 google 试图找到正确的语法或过程,但没有成功。 My desired output would be我想要的 output 是

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

To split the lists by the occurrence of Store in the list you could do something like this:要根据列表中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)

which gives:这使:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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