简体   繁体   English

从 python 的列表中添加 2 个整数

[英]adding 2 integers from a list in python

im doing this exercise basically to add the first 2 integers in a list in python, but my script shows it runs the for loop twice before it iterates to the next integer in a list.我做这个练习基本上是为了在 python 的列表中添加前 2 个整数,但是我的脚本显示它在迭代到列表中的下一个 integer 之前运行了两次 for 循环。

my code is below, i added a print statement so i can see how it iterates the FOR loop inside a WHILE loop.我的代码在下面,我添加了一个打印语句,所以我可以看到它如何在 WHILE 循环中迭代 FOR 循环。

def add2(nums):
    count = 0
    ans = 0
    
    while count <= 2:
        count += 1
        print(f'count: {count}')
        
        for x in nums:
            ans += x
            print(f'ans: {ans}')

HOwever if i run my code, i get this result.但是,如果我运行我的代码,我会得到这个结果。 Why is it adding the value of ans twice before it goes to the next iteration?为什么在进行下一次迭代之前将 ans 的值添加两次? add2([2,3,5]) count: 1 ans: 2 ans: 5 ans: 10 count: 2 ans: 12 ans: 15 ans: 20 count: 3 ans: 22 ans: 25 ans: 30 add2([2,3,5]) 计数:1 回答:2 回答:5 回答:10 计数:2 回答:12 回答:15 回答:20 计数:3 回答:22 回答:25 回答:30

You don't need to overcomplicate this.你不需要把它复杂化。 Just use slicing to return the first to elements of the list.只需使用切片将第一个返回到列表的元素。

simpler code更简单的代码

listNums = [1,2,3,4]
print(float(listNums[0])+float(listNums[1]))

output output

3.0

This is based on your explanation of the problem.这是基于您对问题的解释。


Now using your logic of solving this proble, I would consider removing the while loop altogether but keeping the for loop.现在使用您解决此问题的逻辑,我会考虑完全删除 while 循环但保留 for 循环。 Though keeping the plain for loop will not give us our desired output because it will find the sum of every number in the list.虽然保持简单的 for 循环不会给我们想要的 output 因为它会找到列表中每个数字的总和。 Instead we can cut the list of at two elements.相反,我们可以删除两个元素的列表。 The below code shows how to do that.下面的代码显示了如何做到这一点。

your logic code你的逻辑代码

def add2(nums):
    count = 0
    ans = 0
    for x in nums[:2]:
        ans += x
    print(f'ans: {ans}')
add2([1,2,3,4])

output output

ans: 3

It could be as simple as this:它可以像这样简单:

ans=0
for i in range(len(nums)):
   ans+=nums[i]
   if i > 2:
      break

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

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