I have a function that looks like this (below). I'm using xlrd in python. Whenever I perform the "print path" function, I receive way too many iterations of path. Essentially, what I'm trying to do is compare two columns in excel, and print out a third. That works perfectly, except that the third is printed out too many times, and I believe the problem is the nested loops.
def question():
for x in xrange(sheet.nrows):
buddy = sheet.cell_value(x, 13)
newton = buddy.split(',')
james = sheet.col_values(15)
fred = sheet.col_values(17)
path = sheet.col_values(16)
path2 = sheet.col_values(18)
for i in xrange(len(newton)):
for n in xrange(len(james)) and xrange(len(path)):
if james[n] == newton[i]:
print path[n]
Forgive me, I'm new to python, I only started learning to program a month ago for research. I looked everywhere for potential fixes and I learned about using the zip() and map() functions, however, in trying to do:
for i, n in zip(xrange(len(newton)), xrange(len(james)))
The program didn't print anything at all, even when I just tried print newton[i].
This current code works how I want it to, I'd just like it to iterate once over all the cells, instead of multiple times (as caused by the nesting loop) and I'm not sure how to go about that. Thank you!
This seems closer to what want:
To print some values only once, first collect them into a set; when you're done deciding what needs printing, print out the contents of the set.
There are certainly better ways to code what you're trying to do, but I'm not too sure what that is and this solution doesn't change the logic of your code.
But note that your code is not actually working as you intended: The expression
xrange(len(james)) and xrange(len(path))
is actually the same as justxrange(len(path))
! (Logicaland
returns either a false or the second value.) So the loopis actually doing