我有一个对象列表,希望通过另一个列表中的对象将其分割成对象列表的列表,如下所示:
l = ['x',1,2,3,'a',5,6,1,7]
还有另一个对象列表
s = ['a', 1, 4]
And I wish to get the result so:
[ ['x'], [1, 2, 3], ['a', 5, 6], [1, 7] ]
有没有一种优雅/Pythonic的方式来做到这一点?编辑:我希望每个结果列表的头部都是
我有一个对象列表,希望通过另一个列表中的对象将其分割成对象列表的列表,如下所示:
l = ['x',1,2,3,'a',5,6,1,7]
还有另一个对象列表
s = ['a', 1, 4]
And I wish to get the result so:
[ ['x'], [1, 2, 3], ['a', 5, 6], [1, 7] ]
一个生成器可以在短时间内为您完成这项工作:
def split_on_members(seq, s):
s = set(s)
chunk = []
for i in seq:
if i in s and chunk:
yield chunk
chunk = []
chunk.append(i)
if chunk:
yield chunk
这将会得到:
>>> list(split_on_members(l, s))
[['x'], [1, 2, 3], ['a', 5, 6], [1, 7]]
>>> for group in split_on_members(l, s):
... print group
...
['x']
[1, 2, 3]
['a', 5, 6]
[1, 7]
尝试使用以下两个函数:
The 'return' type
def overlap_split_list(l,s):
l1 = []
l2 = []
for i in l:
if i in s:
l1.append(l2)
l2 = []
l2.append(i)
if l2: l1.append(l2)
return l1
The generator type
def generator_overlap_split_list(l,s):
l2 = []
for i in l:
if i in s:
yield l2
l2 = []
l2.append(i)
if l2: yield l2
输出(全部都相同)
print overlap_split_list(l,s)
print [i for i in generator_overlap_split_list(l,s)]
print list(generator_overlap_split_list(l,s))
overlap_split_list
实际上是所有提交的函数中最快的。 - Gandaro