简体   繁体   English

我如何遍历此列表以获得正确的答案?

[英]How do I iterate through this list to get the right answer?

I'm trying to iterate through a list to get a list of outcomes but the first output is incorrect. 我正在尝试遍历列表以获取结果列表,但第一个输出不正确。 My code is listed below 我的代码在下面列出

with open(csvpath, newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    csv_header = next(csvreader)
    total = 0
    for row in csvreader:
        #print(csvreader)
        total = int(row[1]) -total

I skipped the first line because it contains the header. 我跳过了第一行,因为它包含标题。 I'm essentially supposed to be subtracting (cell B2) 984655 from (cell b1) 867884. But because I'm using a loop, the first value in total is 867884 or (cell B2 - 0). 我本质上应该从(单元格b1)867884中减去(单元格B2)984655。但是由于我使用的是循环,所以第一个值total为867884或(单元格B2-0)。

Also I cannot use pandas for this problem as stipulated by the instructor. 我也不能按照教练的指示使用熊猫来解决这个问题。

I've searched the internet and books to find the right way to find the answer with no success. 我搜索了互联网和书籍,以找到正确的方法来找到答案,但没有成功。

Results should be (cell B1) 867884 minus (cell b2) 984655. But because I'm using a loop, the first value in total is 867884 or (cell B2 - 0). 结果应该是(单元格B1)867884减去(单元格b2)984655。但是由于我使用的是循环,因此第一个值total为867884或(单元格B2-0)。

Your line total = int(row[1]) -total doesn't really make sense because you are only using one column at any point (the row[1] part). 您的行total = int(row[1]) -total真的没有意义,因为您在任何时候都只使用一列(row [1]部分)。 It is not the fact you are using a loop, even with your loop you could do something more like: 这并不是事实,即使使用循环,您也可以执行以下操作:

with open(csvpath, newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    csv_header = next(csvreader)
    for row in csvreader:
        print(int(row[0]) - int(row[1])) # use indexes to specify which column you need

I'll leave it to you to find the best way to only get row B though ;) 我将把它留给您,以找到只获得B行的最佳方法;)

I think I got you most of the way there with this code. 我想我可以通过这段代码获得大部分帮助。 I stuck a variable 'last' that puts the previous iteration outside of the for loop and assigns it after the loop has run. 我粘贴了一个变量“ last”,该变量将先前的迭代置于for循环之外,并在循环运行后分配它。 The problem isn't clean, but hopefully you can take this and solve the problem. 这个问题并不干净,但是希望您可以解决这个问题。

with open('convertcsv.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# csv_header = next(csvreader)
cvsfile = csvreader
last = 0
for value in csvreader:
    b1 = int(value[1])
    b2 = last
    if last == 0:
        next
        total = b1 - b2
        print(total)
        last = int(value[1])

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

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