处理Python中的嵌套循环-选项? [英] Dealing with Nested Loops in Python - Options?

查看:84
本文介绍了处理Python中的嵌套循环-选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的函数.我在python中使用xlrd.每当执行打印路径"功能时,都会收到太多的路径迭代.本质上,我想做的是比较excel中的两列,然后打印出第三列.效果很好,除了第三个被打印了太多次,我相信问题是嵌套循环.

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]

对不起,我是python的新手,我一个月前才开始学习编程研究.我到处寻找潜在的修复程序,但是我学会了如何使用zip()和map()函数,

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)))

即使我只是尝试打印newton [i],程序也根本不打印任何内容.

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!

推荐答案

要只打印一些值,请先将它们收集到一个集中.确定需要打印的内容后,请打印出打印机中的内容.

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.

但是请注意,您的代码实际上并未按预期工作:xrange(len(james)) and xrange(len(path))表达式实际上与xrange(len(path))相同! (逻辑and返回false或第二个值.)因此,循环

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)):

实际上在做

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

这篇关于处理Python中的嵌套循环-选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆