如何确定文本文件中有多少个奇数和偶数?

贾梅夫
def main():

    #Open the numbers.txt file
    File=open ('numbers.txt', 'r')

    #This reads the lines in the file
    for line in File:
        #Convert line to float
        amount=float(line)

        #format and display the amount
        print(format(amount,'.2f'))
        print("\n")

    #close the file
    File.close()

    for amount in range (0,13):
        if (amount%2==0):
            print amount


main()

这是输出的样子:

53
15
21
49
8
98
55
21
76
75
53
28

Total of even numbers:[]
Total of odd numbers:[]
帕德拉克·坎宁安(Padraic Cunningham)

除非您实际上在number.txt中有浮点数,否则只需将其强制转换为int即可:

with open("numbers.txt") as f:
    odds = []
    evens = []
    for num in f:
        num = int(num)
        if num % 2: # if there is a remainder num is odd
            odds.append(num) 
        else: # else it must be even
            evens.append(num)

print("All even numbers: {}".format(evens))
print("All odd numbers: {}".format(odds))
print("Total amount of even numbers: {}".format(len(evens))) # len will be total even nums
print("Total amount of odd numbers: {}".format(len(odds)))

如果您只想要计数:

with open("numbers.txt") as f:
    odd,even = 0, 0
    for num in f:
        num = int(num)
        if num % 2:
            odd += 1
        else:
            even += 1

print("Total amount of even numbers: {}".format(even))
print("Total amount of odd numbers: {}".format(odd))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

数组中有多少个奇数和偶数

使用python 2.7计算一个目录中有多少个文本文件并对其进行编辑

如何交换文本文件中的奇数行和偶数行?

如何读取文本文件并计算其中包含多少个列表?

如何确定目录中有多少个文件而不进行计数?

如何使用PHP删除文本文件中有奇数行的某些文章?

如何查找文件中有多少个单词

数组中有多少个偶数整数(Python)

从文本文件中删除奇数行或偶数行

偶数和奇数编号排序到文本文件中

如何使用vim缩进文本文件的偶数/奇数行

Postgresql:如何确定文本中有多少个字符

如何使用wc和管道来查找某个目录中有多少个文件和目录?

Java-将文本文件中的奇数和偶数词存储到两个单独的数组列表中

如何确定文本文件中的藏宝图(行和列)有多大?

如何让python计算一个目录中有多少个文件?

linux:dir中有多少个文件?

Java I/O 文件中有多少个对象?

计算目录PHP中有多少个文件

Android:如何找出内部存储器中有多少个文件?

Android:如何找出内部存储器中有多少个文件?

如何显示列表中有多少个对象,输入列表名称和对象?

如何检查数组(SWIFT3)中有多少个正确和错误项目

如何知道Cassandra集群中有多少个节点?

如何检测NSArray中有多少个相同的对象

我在文本文件中有私钥。如何生成 .pem 文件或 .cer 文件

当通过 fread 读取编码为 UTF-8 的文本文件时,如何确定一个字符将占用多少字节?

JavaScript中有多少个参数?

ReactJS中有多少个组件?