计算列表中其他元素之间的特定元素数 [英] Count number of specific elements in between other elements in list
问题描述
我正在读取数据文件.行以连续的数字(步)开始,有时在每行之间都有一个0.
I am reading a data file. Rows start with consecutive numbers (steps), and sometimes in between each row there is a 0.
例如:
1
0
2
0
3
4
5
0
0
0
6
0
如何创建一个列表,计算每个步骤之间的0.
How can I create a list that counts the number of 0s in between each step.
我想要一个这样的列表:
I want a list like this:
finalList = [1,1,0,0,3,1]
表示每个步骤包含的0数,即:步骤1具有1个零,步骤2具有1个零,步骤3具有0个零,步骤4具有0个零,步骤5具有3个零,而步骤6具有1个零
which represents the number of 0s each step contains, i.e: step 1 has 1 zero, step 2 has 1 zero, step 3 has 0 zeros, step 4 has 0 zeros, step 5 has 3 zeros and step 6 has 1 zero.
推荐答案
如果您的数据文件看起来完全符合您的描述,则以下代码应该可以工作(例如,除了递增步长和零以外,没有其他数字).
The following code should work if your datafile looks exactly as you described (e.g. no other number except incresing number of step and zeroes).
cur = 0
res = []
with open("file.txt") as f:
for line in f:
if line.strip() == '0':
cur += 1
else:
res.append(cur)
cur = 0
这篇关于计算列表中其他元素之间的特定元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!