[英]Python: split a list into multiple lists based on a specific element
I want to split the following list into sub lists based on an element from that list.我想根据该列表中的元素将以下列表拆分为子列表。
array=['first','sentence','step','second','sentence']
for i in array:
if i!='step':
newlist1.append(i)
else:
(stop appending in newlist1 and start appending in say newlist2)
newlist1 and newlist2 can not be pre declared. newlist1 和 newlist2 不能预先声明。 As the number of elements in the array can vary.由于数组中的元素数量可能会有所不同。 SO I need to find a dynamic way of declaring lists as per the requirement.所以我需要找到一种根据要求声明列表的动态方式。
you could use a list of lists to store these.您可以使用列表列表来存储这些。 So if the value is step then start a new list, if not then append to the last list.因此,如果值为 step 则开始一个新列表,如果不是则 append 到最后一个列表。
from pprint import pprint
lists = [[]]
array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'thrid', 'step', 'some', 'other', 'sentance']
for i in array:
if i == 'step':
lists.append([])
else:
lists[-1].append(i)
pprint(lists)
OUTPUT OUTPUT
[['first', 'sentence'],
['second', 'sentence'],
['thrid'],
['some', 'other', 'sentance']]
You can do the following:您可以执行以下操作:
array=['first','sentence','step','second','sentence']
newlist1 = []
newlist2 = []
check = True
for i in array:
if i!='step' and check:
newlist1.append(i)
else:
check = False
newlist2.append(i)
Try this尝试这个
index = array.index('step')
if index and index < len(array):
newlist1 = array[0:index+1]
newlist2 = array[index+1:]
Although less memory efficient than Chris Doyle's answer, I prefer comprehensions for stuff like this unless they get too verbose to fit on one line.尽管 memory 的效率低于 Chris Doyle 的答案,但我更喜欢对此类内容的理解,除非它们过于冗长而无法放在一行中。
array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'third', 'step', 'some', 'other', 'sentence']
def split_list(lst, sep):
return [i.split() for i in ' '.join(lst).split(sep)]
print(split_list(array, 'step'))
Result结果
[['first', 'sentence'], ['second', 'sentence'], ['third'], ['some', 'other', 'sentence']]
Bonus奖金
If the end goal is a list of sentences instead of a list of lists, just replace the first .split()
with .strip()
.如果最终目标是句子列表而不是列表列表,只需将第一个.split()
替换为.strip()
。
[i.strip() for i in ' '.join(lst).split(sep)]
Returns:回报:
['first sentence', 'second sentence', 'third', 'some other sentence']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.