For loop a values assignment

Question:

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
Asked By: Armando Bridena

||

Answers:

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
Answered By: J V S Krishna

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
Answered By: BENY

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
Answered By: Ben Grossmann
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.