Python 条件for循环的函数

Python 条件for循环的函数,python,loops,conditional,Python,Loops,Conditional,好的,这是我正在使用的完整代码。现在我已经提供了输入和输出。希望我之前提出的荒谬问题更有意义 def get_positions(xs, item): if isinstance(xs, list): for i, it in enumerate(xs): for pos in get_positions(it, item): yield (i,) + pos elif xs == item:

好的,这是我正在使用的完整代码。现在我已经提供了输入和输出。希望我之前提出的荒谬问题更有意义

def get_positions(xs, item):    
    if isinstance(xs, list):
        for i, it in enumerate(xs):
            for pos in get_positions(it, item):
                yield (i,) + pos
    elif xs == item:
        yield ()
blocks = [-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12,14,16]
startcombos = [[-12], [-12, -10], [-12, -10, -8], [-12, -10, -8, -6], [-12, -10, -8, -6, -4], [-12, -10,-8, -6, -4, -2], [-12, -10, -8, -6, -4, -2, 0], [-12, -10, -8, -6, -4, -2, 0, 2], [-12, -10, -8, -6, -4, -2, 0, 2, 4], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14], [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16]]
combos = [[-10], [-10, -8], [-10, -8, -6], [-10, -8, -6, -4], [-10, -8, -6, -4, -2], [-10, -8, -6,-4, -2, 0], [-10, -8, -6, -4, -2, 0, 2], [-10, -8, -6, -4, -2, 0, 2, 4], [-10, -8, -6, -4, -2, 0, 2, 4, 6], [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8], [-10, -8, -6, -4, -2, 0, 2, 4, 6,8, 10], [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12], [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14], [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16], [-8], [-8, -6], [-8, -6, -4], [-8, -6, -4, -2], [-8, -6, -4, -2, 0], [-8, -6, -4, -2, 0, 2], [-8, -6, -4, -2, 0, 2, 4], [-8, -6, -4, -2, 0, 2, 4, 6], [-8, -6, -4, -2, 0, 2, 4, 6, 8], [-8, -6, -4, -2, 0, 2, 4, 6, 8, 10], [-8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12], [-8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14], [-8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16], [-6], [-6, -4], [-6, -4, -2], [-6, -4, -2, 0], [-6, -4, -2, 0, 2], [-6, -4, -2, 0, 2, 4], [-6, -4, -2, 0, 2, 4, 6], [-6, -4, -2, 0, 2, 4, 6, 8], [-6, -4, -2, 0, 2, 4, 6, 8, 10], [-6, -4, -2, 0, 2, 4, 6, 8, 10, 12], [-6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14], [-6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16], [-4], [-4, -2], [-4, -2, 0], [-4, -2, 0, 2], [-4, -2, 0, 2, 4], [-4, -2, 0, 2, 4, 6],[-4, -2, 0, 2, 4, 6, 8], [-4, -2, 0, 2, 4, 6, 8, 10], [-4, -2, 0, 2, 4, 6, 8, 10, 12], [-4, -2, 0, 2, 4, 6, 8, 10, 12, 14], [-4, -2, 0, 2, 4, 6, 8, 10, 12, 14, 16], [-2], [-2, 0],[-2, 0, 2], [-2, 0, 2, 4], [-2, 0, 2, 4, 6], [-2, 0, 2, 4, 6, 8], [-2, 0, 2, 4, 6, 8, 10], [-2, 0, 2, 4, 6, 8, 10, 12], [-2, 0, 2, 4, 6, 8, 10, 12, 14], [-2, 0, 2, 4, 6, 8, 10, 12, 14, 16], [0], [0, 2], [0, 2, 4], [0, 2, 4, 6], [0, 2, 4, 6, 8], [0, 2, 4, 6, 8, 10], [0,2, 4, 6, 8, 10, 12], [0, 2, 4, 6, 8, 10, 12, 14], [0, 2, 4, 6, 8, 10, 12, 14, 16], [2], [2, 4], [2, 4, 6], [2, 4, 6, 8], [2, 4, 6, 8, 10], [2, 4, 6, 8, 10, 12], [2, 4, 6, 8, 10, 12, 14], [2, 4, 6, 8, 10, 12, 14, 16], [4], [4, 6], [4, 6, 8], [4, 6, 8, 10], [4, 6, 8, 10,12], [4, 6, 8, 10, 12, 14], [4, 6, 8, 10, 12, 14, 16], [6], [6, 8], [6, 8, 10], [6, 8, 10, 12], [6, 8, 10, 12, 14], [6, 8, 10, 12, 14, 16], [8], [8, 10], [8, 10, 12], [8, 10, 12, 14], [8, 10, 12, 14, 16], [10], [10, 12], [10, 12, 14], [10, 12, 14, 16], [12], [12, 14], [12, 14, 16], [14], [14, 16], [16]]

temp = []
for i in range(len(startcombos)):   
    for j in list(get_positions(combos,startcombos[i][-1]+2)):
        if j[-1]==0 and combos[j[0]][-1]!=blocks[-1]:

            for k in list(get_positions(combos,combos[j[0]][-1]+2)):                
                if k[-1]==0 and combos[k[0]][-1]!=blocks[-1]:

                    for l in list(get_positions(combos,combos[k[0]][-1]+2)):
                        if l[-1]==0 and combos[l[0]][-1]==blocks[-1]:
                            temp.append(tuple(startcombos[i]))
                            temp.append(tuple(combos[j[0]]))
                            temp.append(tuple(combos[k[0]]))
                            temp.append(tuple(combos[l[0]]))
                            combinations.append(temp)
                            temp = []
这是生成长度为4的temp的代码。如果组合的长度增加,我会在更大的循环中包含另一个条件,如下所示

for i in range(len(startcombos)):   
    for j in list(get_positions(combos,startcombos[i][-1]+2)):
        if j[-1]==0 and combos[j[0]][-1]!=blocks[-1]:

            for k in list(get_positions(combos,combos[j[0]][-1]+2)):                
                if k[-1]==0 and combos[k[0]][-1]!=blocks[-1]:               

                    for l in list(get_positions(combos,combos[k[0]][-1]+2)):
                        if l[-1]==0 and combos[l[0]][-1]!=blocks[-1]:

                            for m in list(get_positions(combos,combos[l[0]][-1]+2)):
                                if m[-1]==0 and combos[m[0]][-1]==blocks[-1]:
                                    temp.append(tuple(startcombos[i]))
                                    temp.append(tuple(combos[j[0]]))
                                    temp.append(tuple(combos[k[0]]))
                                    temp.append(tuple(combos[l[0]]))
                                    temp.append(tuple(combos[m[0]]))                                        
                                    combinations.append(temp)
                                    temp = []
这将生成长度为5的临时值。正如您所注意到的,第一个和最后一个条件和循环发生了变化,中间部分保持不变。如何编写一个函数或任何其他方式,我可以实现它的可变长度

现在我在这里得到的基本上是通过提供特定条件得到的组合。我知道我可以尝试使用itertools中的python组合,但是如果我想要特定的组合,那么生成所有组合是不值得的,而且计算时间也很重要。因此,它将为长度4提供以下输出

combinations[0] = [[-12],[-10],[-8],[-6,-4,-2,0,2,4,6,8,10,12,14,16]]
以此类推,共有364人

对于长度5,它将给出总共1001个组合,其中第一个组合为

combinations[0] = [[-12],[-10],[-8],[-6],[-4,-2,0,2,4,6,8,10,12,14,16]]

我不完全确定我是否正确地解释了你的问题;然而,接下来的是一个相当普遍的练习,它应该在某种程度上对你有所启发。为了便于讨论,我假设您的目标是执行任意数量的嵌套For循环

不过,首先,让我满足Pythonistas阅读本文的要求,说Pythonic的方法可能包括使用函数,也可能包括内置的
filter()
函数

除此之外,我认为您应该熟悉递归的概念,因为它可以让您“天真地”想出解决此类问题的简单方法,而不必依赖像Python这样的漂亮语言来为您提供一个充满生成器函数的很棒的库

假设你在一些列表中有一些列表,比如:

nested = [[a1, a2, a3, ..., ana],
          [b1, b2, b3, ..., bnb],
          ...
          [x1, x2, x3, ..., xnx]]
a1 b1 c1 ... x1
a1 b1 c1 ... x2
...
a2 b1 c1 ... x1
a2 b1 c1 ... x2
...
...
ana bnb cnc ... x(nx - 1)
ana bnb cnc ... xnx
您希望通过伪词法遍历包含这些列表中单个元素的序列,如:

nested = [[a1, a2, a3, ..., ana],
          [b1, b2, b3, ..., bnb],
          ...
          [x1, x2, x3, ..., xnx]]
a1 b1 c1 ... x1
a1 b1 c1 ... x2
...
a2 b1 c1 ... x1
a2 b1 c1 ... x2
...
...
ana bnb cnc ... x(nx - 1)
ana bnb cnc ... xnx
使用普通的静态for循环很难做到这一点,因为您通常必须键入每个循环,对吗?如何键入一些可变数量的for循环?实现这一点的一种简单技巧是使用递归(同样,这不是最具python风格的方法)

递归说,“好的,我有一个问题。这个问题基本上就是用我的一部分数据做一些小的事情,然后递归地在其余的数据上解决同样的问题。当我没有更多的数据要处理时,我可能已经处理完这个子问题了。”

递归的一个简单经典示例是计算一系列数字的和:

def sum_nums(nums):
    # The "base case" is usually checked first. This is when your
    # recursion has run out of things to do, it just returns a simple value.
    if nums == []:
        return 0
    # The "recursive case" is the real meat and potatoes of recursion.
    # It says to take the first number and add it to the sum_nums of the
    # rest of the numbers in the list (which may be empty, hence the base case!).
    else:
        return nums[0] + sum_nums(nums[1:])
想想这个。理解它。冥想它,忘记你理解它。做些迷幻药,再想想。这是非常重要的,能够拉递归黑客出你的屁股在飞行

现在一种更高级的技术是在递归函数中传递值。在这种情况下,它可能会很有用,因为在深入到基本情况之前,您不想做任何事情。如果您愿意的话,我已经省略了基本案例供您自己实现

def print_lexo_lists(items, lists):
    if lists == []:
        # What do you want to do if you've taken a single item from each of your
        # lists and put it in the list called "items"?
    else:
        # Take each item from the current level and pass it down in turn to the
        # next deeper level, adding it to the running list of "items". Remove
        # the current level from the list of "lists" before passing it down.
        # In this way you're "using up" the current level, and the "lists"
        # structure is getting smaller at each level of recursive depth, until
        # you reach the base case (when it is an empty list)
        for current_item in lists[0]:
            print_lexo_lists(items + [current_item], lists[1:])
希望你能在一定程度上理解这一点。我强烈建议您在尝试以下方法之前实现这一点,这确实是在Python中通过生成列表的笛卡尔乘积来执行uber嵌套for循环的正确方法:

from itertools import product
for items in product(*lists):
    print ' '.join(items)

(a) 不清楚你想要实现什么;(b) 不管怎样,你试着做些什么来达到这个目的?我很确定他想要实现循环的可变深度。不太清楚,他提供了一个代码示例。怎么了,伙计们?是的。。请原谅,我不是一个铁杆程序员,因此不熟悉如何用特定的术语向其他程序员描述问题。我试图用函数找到一个解决方案,但它记不住以前的变量,如I、j等。@bioinfoboy:如果你想,你可以在那里提问并插入函数的尝试。你介意为某个输入发布所需的输出吗?