For nested in python

3

Good, I have a list and I want to iterate on it, and then inside that for iterate on the same list from the next value I read until the end.

In a Java-like programming style it would be:

int[10] array;
for (int i=0; i < array.length(); i++)
    for (int j=i+1; j < array.length(); j ++)
        //hacer algo con el array comparando los valores de a[i] y a[j]

How can I do this in pyhton? At first I had this:

for a in array:
     del array[0]
     for a2 in array:
         //hacer algo con el array comparando los valores de a y a2

But it works just for the first iteration .. any help?

    
asked by A77ak 08.05.2016 в 17:01
source

4 answers

1

I do not understand very well what you want to do but you can use enumerate in the following way:

for i, item in enumerate(array):
    for item2 in array[i:]:
        # some code

If you clarify the question a little better maybe we can find a more appropriate answer: -)

    
answered by 08.05.2016 в 21:55
0

The simplest and most effective way is using itertools.combinations :

from itertools import combinations

for (a, b) in combinations(array,  2):
  #comparar los dos elementos del array 
  ... 
    
answered by 09.05.2016 в 03:04
0

This would be the code in Python

int[10] array;
for i in array
    for j in array[i+1:len(j)]
        // hacer algo con los valores de i y j
    
answered by 09.05.2016 в 21:22
0

To define an arrangement in python it is not necessary to define the size of it, at the time of declaring it you can leave it empty or define the values immediately:

No values:

arreglo = []

With values:

arreglo = [5,8,9,4]

Remember that lists in python can grow dynamically with the function append() .

For the handling of the cycles for how you want it, it is as follows:

for i in range(len(arreglo)):
    for j in range((i+1), len(arreglo)):  
        print(arreglo[j])

This syntax is for

The function len() is predefined and returns the size of the array. The range in the forever cycle will begin in 0 unless another value is specified as in the case of the second for.

    
answered by 10.05.2016 в 09:35