gpt4 book ai didi

python - 替换列表中一之间的零

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:44 25 4
gpt4 key购买 nike

假设我有一个如下所示的列表。您如何遍历列表并替换以零为界的零,其中零之间的长度可以变化?

输入:

mylist = [0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0]

输出:

mylist = [0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0]

最佳答案

我认为您可以分两个阶段完成此操作:

  1. 首先,我们获取指示的索引;和
  2. 我们一次拿两个,然后用一个填满这些。

喜欢:

# obtain an iterable of the indices of the ones
ones = iter([i for i,x in enumerate(mylist) if x == 1])

# for every pair of indices
for i0,i1 in zip(ones,ones):
# iterate over the range
for j in range(i0+1,i1):
# and assign 1 to these indices
mylist[j] = 1

这会产生:

>>> mylist
[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0]

关于python - 替换列表中一之间的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com