繁体   English   中英

如何使用python列表将5个连续的一个减少为一个

[英]How to reduce 5 consecutive one to a single one using python list

如果要使用python将连续的5个缩小为一个,请在列表中:如何删除“ 4个并仍然保留原始索引”?

for i in list1:
if list1[counter] == 1:
    if list1[index_begin+1:index_begin+5].count(1)=4:
        print("Delete the last four digits")
        del list1[index_begin+1:index_begin+5]
    else:
        print("There is no match")
index_begin+=1

因此,我要做的是使用另一个列表,在该列表中将我想要的值从list1附加到其中,因此命名为resultList。

这样,我不必担心原始列表的长度发生变化,从而使跟踪索引变得困难。

同样通过使用while循环,它允许我更改在list1中查看的当前索引,i + = 4允许我们跳过其他4个索引,并继续执行列表的其余部分。

您可以根据需要将其转换为功能,从而允许您重复使用它并根据需要发送列表多次。

希望这有道理并能帮助:)

list1 = [1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1]
resultList = []
i = 0

while i < len(list1):
    if list1[i] == 1:
        if list1[i+1:i+5].count(1) == 4:
            resultList.append(1);
            i += 4
        else:
           resultList.append(list1[i])
    else:
        resultList.append(list1[i])

    i+=1
    print(i)

print(resultList)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM