有没有办法按顺序从列表中添加和减去数字?

Is there a way to add and subtract numbers from a list sequentially?

我正在尝试对列表中的每个数字进行加减运算,例如 1 - 1/3 + 1/5 - 1/7 + 1/9。如果您继续这样做,然后将答案乘以 4,您将得到 pi 的近似值。

我有一个名为 ODD 的奇数列表,但我无法如上所示进行加法和减法

我 python 今天刚开始编码,所以这可能是一个简单的错误,但我在网上找不到任何相关信息

谢谢, 亚当

import time
start_time = time.time()


EVEN = []
ODD = []
y = int(1.e2)
x = range(y)
#-----------------------------------------------------------------------------------------
for i in x:
    if i%2 == 0:  
        print(i)
        EVEN.append(i)
    else:
        print(i)
        ODD.append(i)

oc = len(ODD)
ec = len(EVEN)
print("")
print(str(oc) + " " + "Odds Found!")
print(str(ec) + " " + "Evens Found!")
print("--- %s seconds to compute ---" % "{:.2f}".format(((time.time() - start_time))))

time.sleep(3)    #START OF PROBLEM
for i in ODD:
    fract = 1/ODD[i]-1/ODD[i+1]
    sfract = fract + 1/ODD[i+2]
    print(fract)
    print(sfract)


你的问题是因为这个循环

for i in ODD:

迭代列表中的元素(对于每个循环)。这就是为什么 ODD[i] 会导致索引错误或会计算出您不感兴趣的东西的原因。您应该只使用变量 i.

    flag = True
    for i in ODD:
       if flag:
          fract += 1 / i
       else:
          fract -= 1/ i
       flag = not flag

此外,既然你写的是 Python 我建议使用列表理解:

EVEN = [i for i in x if i % 2 == 0]
ODD = [i for i in x if i % 2 == 1]

本程序完全不需要使用任何列表。

arbitrary_number = 1000
sign = 1
total = 0
for n in range(1, arbitrary_number, 2):
   total += sign * 1.0 / n
   sign = -sign
print(4*total)

我写这篇文章的目的是让每一步都清楚。有更简单的方法可以用更少的代码编写它。请记住 Python 是为了简单。通常有一种 明确 的方法可以提出解决方案,但请始终尝试进行试验。

number = 0 #initialize a number. This number will be your approximation so set it to zero.
count = 0 #set a count to check for even or odd [from the formula] (-1)^n
for num in range(1,100,2): #skip even values.
"""
The way range works in this case is that you start with 1, end at 100 or an arbitrary 
number of your choice and you add two every time you increment. 
For each number in this range, do stuff.
"""
    if count%2 == 0: #if the count is even add the value
        number += 1/num #example add 1, 1/5, 1/9... from number
        count += 1 #in order to increment count
    else: #when count is odd subtract
        number -= 1/num  #example subtract 1/3, 1/7, 1/11... from number
        count += 1 #increment count by one

number = number*4 #multiply by 4 to get your approximation.

希望这对您有所帮助,欢迎来到 Python!

让我们检查一下 for 循环:

for i in ODD:
    fract = 1/ODD[i]-1/ODD[i+1]
    sfract = fract + 1/ODD[i+2]
    print(fract)
    print(sfract)

由于您在循环内声明了 fractsfract,它们不计算总和,而是分别计算总和的两项和三项。如果在循环外初始化变量,它们的作用域将允许它们累积值。

对于你正在做的事情,我会为这些变量使用 numpy.float 以防止溢出。

如果需要在列表中顺序加减,可以使用Python切片操作创建2个索引为奇数和偶数的列表。

# Example list
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# [1, 3, 5, 7, 9]
add_list = lst[0::2]

# [2, 4, 6, 8]
subtract_list = lst[1::2]

# Now you can add all the even positions and subtract all the odd
answer = sum(add_list) - sum(subtract_list) # Same as 1-2+3-4+5-6+7-8+9