Python:遍历列表 [英] Python: iterate through a list

查看:94
本文介绍了Python:遍历列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个思维难题,我想使用python解决. 他们给出了4个数字(25、28、38、35),他们希望我们将数字放在... + ...-... = ...中.一种可能的解决方案是25 + 38-35 = 28.我试图从数字中列出来,并通过一些循环和if对其进行迭代: lst = [25,28,38,35]

I´ve a mind challenge riddle that i want to resolve using python. They give 4 numbers (25, 28, 38, 35) and they want us to place the numbers in ...+...-...=... One possible solution is 25+38-35=28. I´ve tried to, making a list from the numbers, iterate them with some loops and an if: lst=[25, 28, 38, 35]

for z in lst:
    for x in lst:
        for c in lst:
            for v in lst:
                 if z+x-c==v:
                     print z,x,c,v

但是,当运行for循环时,它们会重复数字(25 + 25-25 = 25),但那是行不通的.我该如何解决?

But when a run the for loops they repeat the numbers, (25+25-25=25) and that don´t work. How can i solve it?

推荐答案

正如路易斯的评论所暗示的那样,一种好的方法是

As Luis' comment hinted, a good approach is

import itertools

for z, x, c, v in itertools.permutations(lst):
    if z+x-c==v:
        print z,x,c,v

扁平比嵌套好",因为交互式Python提示符下的import this会提醒您:-)

"flat is better than nested", as import this at an interactive Python prompt will remind you:-)

这篇关于Python:遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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