Python) Create a new list with a list

Asked 2 years ago, Updated 2 years ago, 39 views

names = [["Joe", "Smith"], ["Mary", "Smith"], ["Pete", "Smith"], ["Lily", "Smith"], ["Heinz", "Maus"], ["Brigita", "Maus"], ["Juergen", "Maus"], ["Jean", "St. Croix"], ["sophie", "St. Croix"]]

With this array

last_name_list = ['St. Croix', the number of people with the last name, ['sophie', 'Jean'],...] This is a code that creates an array of names for people with the same surname in the front, the number of people with the same surname in the middle, and the names of people with the same surname in the back. I can't think of anything.

Help me! ㅜ<

python list

2022-09-21 15:33

1 Answers

Before you start coding, draw the data structure with your hands.

If you have a list of people in the practice book like above, you can first draw how you can create it according to your purpose, and then move it to the code to solve it easily.

It's annotated.

names = [
  ["Joe", "Smith"], ["Mary", "Smith"], 
  ["Pete", "Smith"], ["Lily", "Smith"], 
  ["Heinz", "Maus"], ["Brigita", "Maus"], 
  ["Juergen", "Maus"], ["Jean", "St. Croix"], 
  ["sophie", "St. Croix"]
]

last_name_dict = {} #A dictionary for gathering people with the same last name
For first_name, last_name in names: # Touring the name,
  If last_name not in last_name_dict: # If the dictionary does not have a corresponding sex,
    last_name_dict[last_name] = [] # Put an empty list with the last name as the key in the dictionary.

  last_name_dict[last_name].append(first_name)# Put the same name in the list of last names.

last_name_list = [] #List for output
For last_name, first_names in last_name_dict.items(): # While touring the dictionary collected above,
  item = [last_name, len(first_names), first_names] # Create a list of last names, people, and names.
  last_name_list.append(item) #Add to list.

print(last_name_list) 

# # [['St. Croix', 2, ['Jean', 'sophie']], ['Maus', 3, ['Heinz', 'Brigita', 'Juergen']], ['Smith', 4, ['Joe', 'Mary', 'Pete', 'Lily']]]

I think you'll find a lot of information that will help you get started at the link below.

http://interactivepython.org/runestone/static/thinkcspy/index.html


2022-09-21 15:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.