本文介绍了在 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)) 和 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 中处理嵌套循环 - 选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 07:39