Dealing with Nested Loops in Python - Options?

放肆的年华 提交于 2019-12-04 06:18:18

问题


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!


回答1:


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.

toprint = set()
for x in xrange(sheet.nrows):
    ...
    if james[n] == newton[i]:
        toprint.add(path[n])


for name in sorted(toprint):
    print(name)

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 just xrange(len(path))! (Logical and returns either a false or the second value.) So the loop

for n in xrange(len(james)) and xrange(len(path)):

is actually doing

for n in xrange(len(path)):
    ...



回答2:


This seems closer to what want:

for new in newton:
    for jam, pat in zip(james, path):
        if jam == new:
            print pat


来源:https://stackoverflow.com/questions/33878986/dealing-with-nested-loops-in-python-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!