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

Categories

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= ["alex@gmail.com", "sam@gmail.com", "email-n"]

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

person-1 = ["alex", "1", "alex@gmail.com"]
person-2 = ["sam", "2", "sam@gmail.com"]
person-n = ["name-n", "roll-n", "email-n"]

How can I code for this in python?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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', 'alex@gmail.com'],
    'person-2': ['sam', '2', 'sam@gmail.com'],
    '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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...