英文:
Hi, am having trouble on how to code [False, False, True, True, True, False, True, True, False] into [[2,3],[6,2]] in python
问题
将[False, False, True, True, True, False, True, True, False]
编码成 [[2, 3], [6, 2]]
的Python代码应该如何写,其中第一个子列表中的2是True的索引起始位置,3是从其索引开始的True元素的总和。被卡在这个问题上。
英文:
How should I code [False, False, True, True, True, False, True, True, False]
into [[2, 3], [6, 2]]
in python, where for the first sublist, 2 is where the True index starts and 3 is the sum of True
elements from where its index starts.
Stuck with this question
答案1
得分: 1
你可以使用 itertools.groupby
和 enumerate
:
from itertools import groupby
[(next(g)[0], 1+len(list(g))) for k, g in groupby(enumerate(lst), key=lambda x: x[1]) if k]
# [(2, 3), (6, 2)]
英文:
You can use itertools.groupby
and enumerate
:
>>> from itertools import groupby
[(next(g)[0], 1+len(list(g))) for k, g in groupby(enumerate(lst), key=lambda x: x[1]) if k]
# [(2, 3), (6, 2)]
答案2
得分: 0
使用简单的循环和标志来跟踪上一个状态:
l = [False, False, True, True, True, False, True, True, False]
out = []
previous = False
for i, x in enumerate(l): # 遍历值和位置
if x: # 如果为True
if not previous: # 并且之前为False,添加新的列表
out.append([i, 1])
else: # 否则增加计数器
out[-1][1] += 1
previous = x # 更新下一次迭代的标志
输出:[[2, 3], [6, 2]]
为了好玩,可以使用 itertools.groupby
来实现一行的替代方法:
from itertools import groupby
out = [[(l:=list(g))[0][0], len(l)]
for k, g in groupby(enumerate(l), key=lambda x: x[1]) if k]
英文:
Use a simple loop and a flag to keep track of the last state:
l = [False, False, True, True, True, False, True, True, False]
out = []
previous = False
for i, x in enumerate(l): # iterate over values and positions
if x: # if True
if not previous: # and we had a False before, add new list
out.append([i, 1])
else: # else increment the counter
out[-1][1] += 1
previous = x # update flag for next iteration
Output: [[2, 3], [6, 2]]
For fun, a one-liner alternative using itertools.groupby
:
from itertools import groupby
out = [[(l:=list(g))[0][0], len(l)]
for k, g in groupby(enumerate(l), key=lambda x: x[1]) if k]
答案3
得分: -1
检查这段代码
lst = [False, False, True, True, True, False, True, True, False]
result = []
start_index = None
true_count = 0
for i, value in enumerate(lst):
if value:
if start_index is None:
start_index = i
true_count += 1
elif start_index is not None:
result.append([start_index, true_count])
start_index = None
true_count = 0
if start_index is not None:
result.append([start_index, true_count])
print(result)
英文:
check this code
lst = [False, False, True, True, True, False, True, True, False]
result = []
start_index = None
true_count = 0
for i, value in enumerate(lst):
if value:
if start_index is None:
start_index = i
true_count += 1
elif start_index is not None:
result.append([start_index, true_count])
start_index = None
true_count = 0
if start_index is not None:
result.append([start_index, true_count])
print(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论