如何使用 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):

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

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

重点是使用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))

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

如果你想总结每一行的索引,你可以这样做:

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/generated/numpy.genfromtxt.html