Home > Back-end >  How do I combine one input to a list of another input in order?
How do I combine one input to a list of another input in order?

Time:11-24

Say I had an input of:

john bob alex liam # names
15 17 16 19 # age
70 92 70 100 # iq

How do I make it so that john is assigned to age 15 and iq of 70, bob is assigned to age 17 and iq of 92, alex is assigned to age 16 and iq of 70, and liam is assigned to age 19 and iq of 100?

Right now I have:

names = input().split()

From there, I know have to make 2 more variables for age and iq and assign them to inputs as well but how do I assign those numbers to the names in the same order?

CodePudding user response:

We can form 3 lists and then zip them together:

names = "john bob alex liam"
ages = "15 17 16 19"
iq = "70 92 70 100"
list_a = names.split()
list_b = ages.split()
list_c = iq.split()
zipped = zip(list_a, list_b, list_c)
zipped_list = list(zipped)  

print(zipped_list)

This prints:

[('john', '15', '70'), ('bob', '17', '92'), ('alex', '16', '70'), ('liam', '19', '100')]

CodePudding user response:

What is the expected output?

Assuming a dictionary, that is the canonical way to link key:values, you can use a dictionary comprehension:

text = '''john bob alex liam # names
15 17 16 19 # age
70 92 70 100 # iq'''

d = {key: [age, iq] for key, age, iq in 
     zip(*(s.split() for s in 
           (s.split(' #', 1)[0] for s in 
            text.split('\n'))))}

Output:

{'john': ['15', '70'],
 'bob': ['17', '92'],
 'alex': ['16', '70'],
 'liam': ['19', '100']}

NB. if you want integers, use key: [int(age), int(iq)]

If you want tuples:

out = list(zip(*(s.split() for s in 
                 (s.split(' #', 1)[0] for s in text.split('\n')))))

Output:

[('john', '15', '70'),
 ('bob', '17', '92'),
 ('alex', '16', '70'),
 ('liam', '19', '100')]

CodePudding user response:

Only if you have the same amount of each type (5 names, 5 ages and 5 iqs) you could store all the names in a list, all ages in another, and all iqs in another. Then, assign the first element of the names list with the first element of the ages list, and with the first element of the iqs list and so on

names = ["John", "Bob", "Alex", "Liam"]
ages = [15, 17, 16, 19]
iqs = [70, 92, 70, 100]

Then, in order to, for example, print this, you could

print(names[0], ages[0], iqs[0])
  • Related