如何在python中执行C ++样式(索引)嵌套循环? [英] How to do C++ style(indexed) nested loops in python?

查看:99
本文介绍了如何在python中执行C ++样式(索引)嵌套循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中的以下命令等效什么?

What is the equivalent of the following in python?

for (i=0; i<n; i++)
    for (j=i+1; j<n; j++)
        //do stuff with A[i], A[j]

或者从某种意义上讲,以下内容.每次循环结束后,它还应从A中删除该元素.

Or in some sense, the following. It should also remove the element from A at the completion of each round of the loop.

for a in A:
    for a' in A/{a}: #i.e. rest of the elements of A
        #do something with a,a'
    #remove a from A

是否存在不使用enumerate()的pythonic方法?

Is there a pythonic way of doing this without using enumerate()?

很抱歉,描述不正确.

Sorry for the bad description.

  1. 在第一个示例中,我的意思是使用i& j仅作为索引.它们的值无关紧要.它只是后者的大致C ++等效项.

  1. In the first example, I mean to use i & j only as indices. Their values do not matter. Its just a rough c++ equivalent of the latter.

外部循环执行了n次.对于外循环的每次迭代,将执行(n-1),(n-2)... 0次内部循环.

The outer loop is executed n times. The inner loop is executed (n-1), (n-2)...0 times for each iteration of the outer loop.

也许这可能会有所帮助(伪代码):

Maybe this might help (pseudocode):

function next_iteration(list):
    head = first element
    tail = remaining elements #list
    each element in tail interacts with head one by one
    next_iteration(tail)

PS:以上所有代码示例均为伪代码.我正在尝试表达一种我心中仍含糊不清的内容.

PS: All code samples above are pseudocodes. I'm trying to express something that is still a bit vague in my mind.

推荐答案

由于您的两个问题不同,因此以下是第二个问题的解决方案:

Since your two questions are different, here is solution for your second problem:

for i in xrange(len(A)):
    for j in xrange(len(A)):
        if i != j:
            do_stuff(A[i], A[j])

使用 itertools(我认为使用随附的电池是非常Python的方法!):

or using itertools (I think using the included batteries is very pythonic!):

import itertools

for a, b in itertools.permutations(A, 2):
    do_stuff(a, b)

这会将do_stuff应用于A中2个不同元素的所有组合.我只想使用以下方法存储结果:

This applies do_stuff to all combinations of 2 different elements from A. I you want to store the result just use:

[do_stuff(a, b) for a, b in itertools.permutations(A, 2)]

这篇关于如何在python中执行C ++样式(索引)嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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