将列表拆分为仅包含 1 的列表
Split list into lists containing only 1s
我在 python 中有这个列表:
[100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
我如何拆分给定列表(以及其他包含 1 的列表)以便我得到仅包含相邻 1 的子列表 - 因此结果将是:
[ [1, 1, 1], [1, 1, 1, 1], [1] ]
我想我想构建一个函数,以某种方式检测“外部”1 作为列表分隔点:
我想可能有一种方法可以使用 itertools
' takewhile
/dropwhile
或其他东西,但这个简单的 for 循环可以做到:
l = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
res = []
tmp = []
for i in l:
if i == 1:
tmp.append(i)
elif tmp:
res.append(tmp)
tmp = []
if tmp:
res.append(tmp)
print(res)
输出:
[[1, 1, 1], [1, 1, 1, 1], [1]]
from itertools import groupby
inputlist = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
result = [list(grp) for val, grp in groupby(inputlist) if val == 1]
groupby
没有键只是将相同值的 运行 分组,在每个循环中产生该值的一个副本和该 运行 个值的迭代器。您检查这是否是 1
的 运行(丢弃任何不是的组),如果是,列出该组以创建下一个子 list
.
试试这个:
def get_one_lists(the_list):
result = [] # Initialize list of lists
among_ones = False # Flag whether we are now among 1's
for e in the_list:
if e == 1:
if among_ones:
result[-1].append(1) # Already among 1's. Append this 1 too.
else:
result.append([1]) # Stumbled upon a new sequence of 1's
among_ones = True
else:
among_ones = False
return result
测试:
my_list = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
print(get_one_lists(my_list))
my_list = [1, 100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
print(get_one_lists(my_list))
输出:
[[1, 1, 1], [1, 1, 1, 1], [1]]
[[1], [1, 1, 1], [1, 1, 1, 1], [1]]
我在 python 中有这个列表:
[100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
我如何拆分给定列表(以及其他包含 1 的列表)以便我得到仅包含相邻 1 的子列表 - 因此结果将是:
[ [1, 1, 1], [1, 1, 1, 1], [1] ]
我想我想构建一个函数,以某种方式检测“外部”1 作为列表分隔点:
我想可能有一种方法可以使用 itertools
' takewhile
/dropwhile
或其他东西,但这个简单的 for 循环可以做到:
l = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
res = []
tmp = []
for i in l:
if i == 1:
tmp.append(i)
elif tmp:
res.append(tmp)
tmp = []
if tmp:
res.append(tmp)
print(res)
输出:
[[1, 1, 1], [1, 1, 1, 1], [1]]
from itertools import groupby
inputlist = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
result = [list(grp) for val, grp in groupby(inputlist) if val == 1]
groupby
没有键只是将相同值的 运行 分组,在每个循环中产生该值的一个副本和该 运行 个值的迭代器。您检查这是否是 1
的 运行(丢弃任何不是的组),如果是,列出该组以创建下一个子 list
.
试试这个:
def get_one_lists(the_list):
result = [] # Initialize list of lists
among_ones = False # Flag whether we are now among 1's
for e in the_list:
if e == 1:
if among_ones:
result[-1].append(1) # Already among 1's. Append this 1 too.
else:
result.append([1]) # Stumbled upon a new sequence of 1's
among_ones = True
else:
among_ones = False
return result
测试:
my_list = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
print(get_one_lists(my_list))
my_list = [1, 100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
print(get_one_lists(my_list))
输出:
[[1, 1, 1], [1, 1, 1, 1], [1]]
[[1], [1, 1, 1], [1, 1, 1, 1], [1]]