Dealing with Nested Loops in Python - Options?

后端 未结 2 1558
南旧
南旧 2021-01-27 18:49

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

相关标签:
2条回答
  • 2021-01-27 19:11

    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)):
        ...
    
    0 讨论(0)
  • 2021-01-27 19:14

    This seems closer to what want:

    for new in newton:
        for jam, pat in zip(james, path):
            if jam == new:
                print pat
    
    0 讨论(0)
提交回复
热议问题