Looping with condition

for loop
for loop example
while loop
do while loop in c
for loop in python
for loop c++
do loop
loop statements in c

I want to do the looping with condition.

In [1]  : data_1
Out [1] :
text1
text2

In [2]  : data_2
Out [2] :
a
b
c
d
e

I want every text in data_1 only works for 2 text in data_2. So, the output will be like this.

text1, a
text1, b
text2, c
text2, d

and it will be stop if data_1 didn't have any data. I typed the script like this, but didn't work.

for i in range(len(data_1)):
    for j in range(0, len(data_2)):
            print(i, j)

and the output showed like this.

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4

One way to do this is to use the itertools library and zip(), e.g.:

In []:
import itertools as it
n = 2   # No. of repetitions
list(zip(it.chain.from_iterable(it.repeat(x, n) for x in data_1), data_2))

Out[]:
[('text1', 'a'), ('text1', 'b'), ('text2', 'c'), ('text2', 'd')]

Or if you want to print() out each element:

In []:
for x in zip(it.chain.from_iterable(it.repeat(x, n) for x in data_1), data_2):
    print(', '.join(x))

Out[]:
text1, a
text1, b
text2, c
text2, d

C Loops: For, While, Do While, Break, Continue with Example, The boolean expression after the if statement is called the condition. If it is true, then all the indented statements get executed. What happens if the condition is  Loop with Condition Use the Loop with Condition action A tool for building the processes, logic, and direction within workflows. to run a set of child actions until a specified expression is met. The expression includes one or many conditions.

Here is a simple (although less pythonic than AChampion's) way to achieve what you want:

ind = 0
for i in data_1:
    for _ in range(2):
        print('{}, {}'.format(i, data_2[ind]))
        ind += 1

condition controlled loops, What are Loops? In looping, a program executes the sequence of statements many times until the stated condition becomes false. A loop  In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false.

data_1 = ['text1','text2']
data_2 = ['a','b','c','d','e']

print '\n'.join([data_1[i//2]+','+data_2[i] for i in range(min(len(data_1)*2,len(data_2)))])

Output:

text1,a
text1,b
text2,c
text2,d

For a more generalized

from math import ceil
data_1 = ['text1','text2']
data_2 = ['a','b','c','d','e','f','g']

t = int(ceil(len(data_2)/float(len(data_1))))
print '\n'.join([data_1[i/t]+','+d for i,d in enumerate(data_2)])

This will work as long as data_1 is shorter than data_2

Output:

text1,a
text1,b
text1,c
text1,d
text2,e
text2,f
text2,g

Visual Basic/Loops, The <condition> is a boolean expression. We generally make the <statement> be a block. The following example shows the conventions used in this course for  A ‘Do While’ loop allows you to check for a condition and run the loop while that condition is met (or is TRUE). There are two types of syntax in the Do While Loop. Do [While condition] [Code block to Execute] Loop. and. Do [Code block to Execute] Loop [While condition]

data_1 = ['text1','text2']
data_2 = ['a','b','c','d']

for i in range (len(data_1)):
    if i == (len(data_2)/2 -1):
        k=i+1
        data_2 = data_2[k:]
        for j in range(len(data_1)):
            print (data_1[i],data_2[j])
    else:
        for j in range(len(data_1)):
            print (data_1[i],data_2[j])

Loops: while and for, A While Loop repeats or loops WHILE a condition is true. A While loop consists of three parts: The While key word that begins the loop; the condition to be tested  The following is a list of topics that explain how to use Loops and Conditional Statements in Oracle/PLSQL: CURSOR FOR LOOP. REPEAT UNTIL LOOP. Conditional Statements. IF-THEN-ELSE Statement.

Perhaps a less fancy approach would be to double data_1:

data_1 = ['text1','text2', 'text3', 'text4', 'text5', 'text6']
data_2 = ['a','b','c','d', 'e,', 'f', 'g']

double_data_1 = []
[ double_data_1.append(e) for e in data_1 for ee in range(2) ]
res = zip(double_data_1, data_2)
list(res)

[('text1', 'a'),
 ('text1', 'b'),
 ('text2', 'c'),
 ('text2', 'd'),
 ('text3', 'e,'),
 ('text3', 'f'),
 ('text4', 'g')]

4. Conditionals and loops, While loops check for the stopping condition first, and may not execute the body of the loop at all if the condition is initially false. Syntax: while( condition ) body;. CNCCookbook’s G-Code Tutorial Introduction to Conditions and Looping. This installment of our Mini-Tutorial on G-Code Macros is all about three important constructs in G-Code Macro Programming:

Conditional statements and loops, This expression can also declare variables. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If  Do loop is a technique used to repeat an action based on a criteria. Syntax: Do While Condition Statement(s) Loop It will execute the statements if the condition is true,The following is example on Dow While:

9.7 Looping, Control structures set a condition and tell R what to do when that condition is met or not met. And unlike some kids, R will always do what we tell it to! You can learn  It seems like the second condition in the second for loop is not being considered. My code runs this way: for (i in 1:nrow(mydata)) { for (j in 1:nrow(mydata) && j!=i ) { Statements.

C Programming Course Notes, This MATLAB function evaluates an expression, and repeats the execution of a group of statements in a loop while the expression is true. I tried giving a check condition inside the loop and it worked fine. I changed the value of lv_diff to 600, in that case it doesn't go into the loop itself. Can anybody explain me what is the real problem with this logic? Also would like to know if there is any rule that says this type of conditions should not be used within the loop.

Comments
  • Are data_1 and data_2 lists of strings?
  • What would the output be if we keep data_1 = ['text1', 'text2'] but change data_2 = ['a', 'b', 'c', 'd', 'e', 'f']? Would it be the same, or would you expect 6 lines of output?
  • Alternatively it.chain.from_iterable(it.repeat(x, n) for x in data_1) can be written as (x for x in data_1 for _ in range(n)), which is more readable IMO.
  • True, and is definitely more readable than my original approach: it.chain.from_iterable(zip(*it.tee(data_1, n)))
  • Thank you @AChampion it really helps me out
  • If you want a counter then itertools.count() is often a good choice, ind = itertools.count() then data_2[next(ind)] and you can eliminate ind += 1. You could also then turn this into a list comprehension if the results were needed.
  • It would be better to not hard-code the 2. Try to handle data_1 and data_2 of any lengths.
  • The 2 is hard-coded because OP wants each item in data_1 to be outputted twice. This solution will work as long as len(data_2) >= 2 * len(data_1) which seems to be the case. If not, appropriate handling logic should be added to catch/prevent the ensuing IndexError.
  • Maybe the OP wants each item in data_1 to be outputted twice. But maybe they want a more dynamic solution. Eg, if data_2 contains 6 items (and data_1 stays the same) then they may want each data_1 to be outputted three times.
  • Thank you @Farhan for the help.
  • Noted. I will change /. As for hard-coding 2, my previous answer which I deleted could handle variable length but the problem is I dont know what the OP wanted if lengths were different
  • It's not a good idea to guess, since it's so easy to guess wrongly. ;) But unfortunately the OP isn't responding to requests for clarification.
  • BTW, you really should seriously consider migrating to Python 3, Python 2 reaches its official End of Life some time in 2020. In the mean time, you can get Python 3 division behaviour in Python 2.6+ with from __future__ import division at the top of your imports. That way you wouldn't need that float() call. In fact, you should do from __future__ import print_function, division to get Python 3 printing as well. That'll help you get used to Python 3, and it'll make it easier for Python 3 users to run your code.