如何在列表中每次连续的零运行中删除除x中的所有零以外的所有零? [英] How can I delete all zeros except for x of them in every run of consecutive zeros within a list?
本文介绍了如何在列表中每次连续的零运行中删除除x中的所有零以外的所有零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于每次运行x
或Python列表中的多个连续零,我想在运行中删除所有零,但x
除外.如果为x = 0
,则删除所有零.
For every run of x
or more consecutive zeros in a list in Python, I would like to del all zeros in the run except for x
of them. If x = 0
, then delete all zeros.
我在想一个Python函数,它将一个列表L
和一个数字x
作为输入.
I was thinking of a Python function that took a list, L
, and a number, x
, as inputs.
例如,让L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8]
.
- 如果
x = 0
,则返回L = [7, 12, 2, 27, 10, 8]
- 如果
x = 1
,则返回L = [7, 0, 12, 0, 2, 0, 27, 10, 0, 8]
- 如果
x = 2
,则返回L = [7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8]
- 如果
x = 3
,则返回L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8]
- 如果为
x = 4
,则返回L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8]
(与原始的L
相同) - 如果为
x >= 5
,则返回原始L,因为没有5个或更多连续零的游程.
- If
x = 0
, then returnL = [7, 12, 2, 27, 10, 8]
- If
x = 1
, then returnL = [7, 0, 12, 0, 2, 0, 27, 10, 0, 8]
- If
x = 2
, then returnL = [7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8]
- If
x = 3
, then returnL = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8]
- If
x = 4
, then returnL = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8]
(Same as originalL
) - If
x >= 5
, then return original L as there are no runs of 5 or more consecutive zeros.
衷心感谢您的帮助.
推荐答案
作为生成器很容易做到.如果要删除零游程的新列表,请在list
构造函数中将对它的调用包装起来.
This is easy to do as a generator. Wrap your call to it in a list
constructor if you want a fresh list with the zero-runs removed.
def compact_zero_runs(iterable, max_zeros):
zeros = 0
for i in iterable:
if i == 0:
zeros += 1
if zeros <= max_zeros:
yield i
else:
zeros = 0
yield i
这篇关于如何在列表中每次连续的零运行中删除除x中的所有零以外的所有零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文