Jan Cajthaml
Jan Cajthaml

Reputation: 403

For loop in python (Simple)

I have a really really simple question that I struggle with :)

I need to iterate over list of truples in means of lower triangle matrix in python


python code

dataset = #list of truples

for i, left in enumerate(dataset):
  for j, right in enumerate(dataset):
    if j <= i : continue    #fixme there should be a better way
    foo(left,right)

target pseudo code

for( i=0; i<size; i++ )
  for( j=i; j<size; j++ )
    foo(data[i],data[j])

Thank you very very much :)

Upvotes: 3

Views: 959

Answers (2)

neuromusic
neuromusic

Reputation: 114

This is a good place to use itertools.

import itertools

for (left,right) in itertools.combinations(data,2):
    foo(left,right)

Upvotes: 0

Costa Halicea
Costa Halicea

Reputation: 160

Based on the pseudo code this should be something like this:

for i in range(0, len(data)):   
  for j in range(i, len(data)):
    foo(data[i],data[j])

also u can do it with one liner:

[foo(data[i],data[j]) for i in range(0, len(data)) for j in range(i, len(data)]

Upvotes: 5

Related Questions