[英]Unsure of how to reference an element within a list to an if statement
for row in range(numLines):
if row[intIdx](3) is not 'DEP':
check_total += float(row[intIdx][2])
else:
deposit_total += float(row[intIdx][2])
I'm very green to python, coming from vb.net, so it may not make sense. 我对来自vb.net的python非常满意,所以这可能没有意义。
I have a list that has 4 elements per line with a comma delimiter. 我有一个列表,每行有4个元素,并带有逗号分隔符。 This block of code is supposed to run through each "row" and compare the 4th element with the parameter of the if statement, and to carry on whatever operation depending on the results.
该代码块应该遍历每个“行”,并将第4个元素与if语句的参数进行比较,并根据结果进行任何操作。
I keep getting the 'int' object is not a subscriptable error, which I suspect that it might be more errors on top of this one. 我不断得到'int'对象不是一个可以描述的错误,我怀疑这可能是更多错误。
I just need an explanation of what is going on and how I can improve the code so that my program can run properly. 我只需要说明正在发生的事情以及如何改进代码,以便程序可以正常运行。
I thank everyone for any input they can give me. 我感谢大家给我的任何意见。
This line is your problem: 这行是你的问题:
if row[intIdx](3) is not 'DEP':
You need to create an array from the row, currently it is just a string. 您需要从该行创建一个数组,当前它只是一个字符串。 Here is the code:
这是代码:
for row in range(numLines):
rowarray = row.split(',')
if rowarray[3] != 'DEP':
check_total += float(rowarray[2])
else:
deposit_total += float(rowarray[2])
You are looping through a range. 您正在遍历范围。 numLines is either the size of a list or the length of an input file.
numLines是列表的大小或输入文件的长度。 Honestly I did not quite get your idea, but I think that is what you are trying to do.
老实说,我并没有完全理解您的想法,但是我认为这就是您想要做的。
with open('Transactions.txt') as file:
for line in file:
rowarray = line.split(',')
if rowarray[3] != 'DEP':
check_total += float(rowarray[2])
else:
deposit_total += float(rowarray[2])
When you write 当你写
for i in range(nuList):
you are basically doing 你基本上在做
for i in [1, 2, 3, ...., N]: # being N the size of your list
Therefor you are not looping through your data but rather through the range of indexes. 因此,您不是遍历数据,而是遍历索引范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.