简体   繁体   中英

Using of 2 for loop

I want to get information from user, and show it with for loop. I wrote this code:

name=["Name","Age","Gender"]
n=str(input())
a=int(input())
g=str(input())
nameinput=[n,a,g]
for i in name:
    for j in nameinput:
        print(i,j)

I expect the output of code to be:

Name Fuad, Age 18, Gender M

but the actual output is

Name Fuad Name 18 Name M Age Fuad Age 18 Age M Gender Fuad Gender 18 Gender M

How I can fix this problem and please can you explain why my code isn't running

You are doing nested loops which iterates the cartesian product (every element of name is paired with every element of nameinput ). You want to do pair-wise iteration of multiple iterables, which is achieved by zip :

for i, j in zip(name, nameinput):
    print(i,j)

The workings of zip can be illustrated by the following example:

list(zip([1, 2, 3], [4, 5, 6]))
# [(1, 4), (2, 5), (3, 6)]

Nested loops, however, would do:

>>> [(i, j) for i in [1, 2, 3] for j in [4, 5, 6]]
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

If you think through your loop code step-by-step, that logic should become clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM