Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

create some list for n number of person from the list of multiple person's attributes in Python

I have some lists describe some attribute of 'n' number of person( say person-1, person-2, ..... person-n), like following type of lists (according to attribute):

name_list= ["alex", "sam", "name-n"]
roll_list= ["1", "2", "roll-n"]
email_list= ["[email protected]", "[email protected]", "email-n"]

Now I need to create another n number of lists according to person like this:

person-1 = ["alex", "1", "[email protected]"]
person-2 = ["sam", "2", "[email protected]"]
person-n = ["name-n", "roll-n", "email-n"]

How can I code for this in python?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this :

person_dict = {f'person-{n+1}' : [name, roll, email] for n, (name, roll, email) in enumerate(zip(name_list, roll_list, email_list))}

Output :

person_dict would be :

{
    'person-1': ['alex', '1', '[email protected]'],
    'person-2': ['sam', '2', '[email protected]'],
    'person-3': ['name-n', 'roll-n', 'email-n']
}

In this way, you won't have n number of different variables assigned to their corresponding list, but you'll have one dictionary and you can look up keys from that dictionary with person_dict.get(key).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...