Home > Software design >  For loop a values assignment
For loop a values assignment

Time:11-08

I have this dataset, where I will use to fill missing values.

In [1]: sex_class = ['female','male']
        pclass = [1,2,3]
        fill_values = [34,40,29,18,24,25]

In [2]: for i in pclass:
            for j in sex_class:
                print(i,j)
Out[2]: 1 female
        1 male
        2 female
        2 male
        3 female
        3 male

How can I make it so that the output will appear as:

1 female 34
1 male   40
2 female 29
2 male   18
3 female 24
3 male   25

CodePudding user response:

You could do the following:

from itertools import product

sex_class = ['female','male']
pclass = [1,2,3]
fill_values = [34,40,29,18,24,25]

for (p,sex),val in zip(product(pclass,sex_class),fill_values):
    print(f"{p} {sex:<6} {val}")

The resulting output:

1 female 34
1 male   40
2 female 29
2 male   18
3 female 24
3 male   25

CodePudding user response:

You could do with pop for the list

sex_class = ['female','male']
pclass = [1,2,3]
fill_values = [34,40,29,18,24,25]
for i in pclass:
     for j in sex_class:
            print(i,j,fill_values.pop(0))
1 female 34
1 male 40
2 female 29
2 male 18
3 female 24
3 male 25

CodePudding user response:

I am thinking the fill_values as the list and writing the answer.

count = 0
for i in pclass:
    for j in sex_class:
        print(i,j,fill_values[count])
        count  = 1
  • Related