Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double for loops in python

Tags:

python

I am trying to get a list of file names in order. Something like

files-1-loop-21
files-1-loop-22
files-1-loop-23
files-1-loop-24
files-2-loop-21
files-2-loop-22
files-2-loop-23
.
.
.
and so on

As for testing I have written python code as below:

code sample_1:

for md in range(1,5):
   for pico in range(21,25):
      print md, pico

It gives me pair of number such as:

  `1 21
   1 22
   1 23
   1 24
   2 21
   2 22
   2 23
   2 24
   3 21
   3 22
   3 23
   3 24
   4 21
   4 22
   4 23
   4 24

`

if I use:

code sample_2:

 for md in range(1,5):
   for pico in range(21,25):
  print "file-md-loop-pico"

I get

  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico

How (code sample_2) should be altered to get the file lists as I wanted (as shown in the beginning of this post) in python?

Thanks in advance.

Regards

like image 287
Vijay Avatar asked Jan 17 '13 12:01

Vijay


People also ask

How do you double a loop in Python?

First, Write an outer for loop that will iterate the first list like [for i in first] Next, Write an inner loop that will iterate the second list after the outer loop like [for i in first for j in second] Last, calculate the addition of the outer number and inner number like [i+j for i in first for j in second]

What is a double for loop?

A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop runs many times inside the outer loop.

How do you write two for loops in one line Python?

Summary: To write a nested for loop in a single line of Python code, use the one-liner code [print(x, y) for x in iter1 for y in iter2] that iterates over all values x in the first iterable and all values y in the second iterable.

How do I combine two for loops?

num = 224 list1 = [] for i in range(2, num): if num % i == 0: list1. append(i) for i in range(2, num): if num % i == 0: print(num, 'is not prime and can be divided by the following numbers:\n', list1) break else: print(num, 'is Prime. ')


1 Answers

Try this:

for md in range(1,5):
   for pico in range(21,25):
      print "file-{0}-loop-{1}".format(md, pico)

Or:

from itertools import product
for md, pico in product(range(1,5), range(21,25)):
    print "file-{0}-loop-{1}".format(md, pico)
like image 122
Artsiom Rudzenka Avatar answered Oct 12 '22 15:10

Artsiom Rudzenka