繁体   English   中英

如何使用python求和文本文件中的奇数索引数字

[英]How do I sum the odd indexed numbers in a text file using python

我有一个文本文件,内容为:1、2、3、4、5。 我想编写一个仅在文本文件中添加奇数索引号的代码。

我已在文本文件中添加了所有数字的代码。

odd_indexed = 0
openthefile = open('GOT_ratings.txt', "r")

for line in openthefile:
    for num in line.split(','):
        odd_indexed = odd_indexed + float(num.strip())

print("The sum of your numbers is %.1f" %(odd_indexed))

我希望它加1 + 3 + 5 = 9

这应该可以解决问题(如果您希望索引的结果从1开始,请编辑==1 1):

for i,num in enumerate(line.split(',')):
    if (i%2==0):
        odd_indexed+=float(num)

enumerate给出索引以及值本身,并且您可以检查哪一个是奇数(或者在描述所需输出的情况下甚至是奇数)。

如果您想总结每行的索引,则可以执行以下操作:

for line in openthefile:
    odd_indexed += sum([int(x) for i, x in enumerate(line.split(',')) if i%2==0])
odd_indexed = 0
i=0
openthefile = open('GOT_ratings.txt', "r")

for line in openthefile:
    for num in line.split(','):
        if i%2!= True:
          odd_indexed = odd_indexed + float(num.strip())
          i+=1
        else:
          odd_indexed = odd_indexed 
          i+=1


print("The sum of your numbers is %.1f" %(odd_indexed))

numpy的genfromtxt的一线解决方案。 无需执行循环。

对于偶数索引:

import numpy as np
ans=sum(np.genfromtxt('GOT_ratings.txt',delimiter=',')[::2])

对于奇数索引:

import numpy as np
ans=sum(np.genfromtxt('GOT_ratings.txt',delimiter=',')[1::2])

有关genfromtxt的信息可以在以下位置找到: https ://docs.scipy.org/doc/numpy/reference/produced/numpy.genfromtxt.html

关键是使用enumerate ,这样就可以处理索引。 但是1、3、5的索引是0、2、4,这是偶数,也不是奇数。 这是示例代码:

odd_indexed = 0
line = '1, 2, 3, 4, 5'
for i, num in enumerate(line.split(',')):
    # for beginner
    if i % 2 == 1:
        odd_indexed = odd_indexed + float(num.strip())

    # more concise way
    # odd_indexed += float(num.strip()) if i % 2 else 0

print("The odd sum of your numbers is %.1f" % (odd_indexed))

希望对您有所帮助,如有其他问题,请发表评论。 :)

暂无
暂无

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

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