[英]How can I change this function so that it returns a list of the number of even digits in a file?
def evens(number_file: TextIO) -> List[int]:
lst = []
line = number_file.readline().strip()
while line != '':
evens = 0
line = number_file.readline().strip()
while line.isdigit():
evens = evens + int(line)
line = number_file.readline().strip()
lst.append(evens)
return last
in this example the file 'numbers.txt' looks like this:在此示例中,文件“numbers.txt”如下所示:
START开始
1 1
2 2
END结尾
START开始
3 3
END结尾
START开始
4 4
5 5
6 6
END结尾
Each line is either an int or 'START' or 'END' I want to make a function that returns the number of evens in each section so when the code tuns on this file, it should return the list [1, 0, 2].每行都是一个 int 或 'START' 或 'END' 我想创建一个函数来返回每个部分中的偶数数量,因此当代码在此文件上运行时,它应该返回列表 [1, 0, 2] . Could someone please help me?
有人可以帮我吗?
import numpy as np
def main():
line = [1,4,5,6,8,8,9,10]
evens = np.array()
for l in line:
if (l % 2) == 0:
np.append(evens, l)
return evens
if __name__ == '__main__':
main()
Without your txt
file and the code to read it in, this is the best I can do.没有你的
txt
文件和读取它的代码,这是我能做的最好的。
When writing new code, it's a good idea to start small and then add capabilities bit by bit.编写新代码时,最好从小处着手,然后一点一点地添加功能。 eg, write code that works without worrying about sections first, then update to work with sections.
例如,首先编写无需担心节的代码,然后更新以使用节。
But anyway, here's some revised code that should work:但无论如何,这里有一些应该可以工作的修改后的代码:
def evens(number_file: TextIO) -> List[int]:
lst = []
line = number_file.readline().strip()
while line != '':
evens = 0
# ignore all text lines
while !line.isdigit():
line = number_file.readline().strip()
# process number lines
while line.isdigit():
if int(line) % 2 == 0:
evens = evens + 1
line = number_file.readline().strip()
lst.append(evens)
return lst
And here's a version that may be simpler ( for
loops in Python can often make your life easier, eg when processing every row of a file):这是一个可能更简单的版本(Python 中的
for
循环通常可以让您的生活更轻松,例如在处理文件的每一行时):
def evens(number_file: TextIO) -> List[int]:
lst = []
for row in number_file:
line = row.strip()
if line == 'START':
# new section, start new count
lst.append(0)
elif line.isdigit() and int(line) % 2 == 0:
# update current count (last item in lst)
lst[-1] += 1
return lst
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.