Python中基于名称合并两个嵌套列表的技术求助
Hey there! Since you're new to Python, let's break this down in a straightforward way. The core idea here is to make name lookups quick and easy using a dictionary, then combine entries where names match. Let's dive in:
First, let's fix a small syntax detail from your original code—text values like names and dates need to be wrapped in quotes in Python, otherwise the interpreter will treat them as undefined variables:
FirstList = [['joe', '12-mar', 2101], ['mike', '13-mar', 2102], ['mario', '15-mar', 2103]] SecondList = [[2524, 'joe'], [2786, 'mike']]
Step 1: Create a Name-to-Number Mapping
We'll convert SecondList into a dictionary where each key is a name, and the value is the corresponding number. This lets us check if a name exists in SecondList in a single, fast step:
# Build a dictionary to map names from SecondList to their numbers name_number_map = {item[1]: item[0] for item in SecondList}
Step 2: Merge Matching Entries
Now we loop through each entry in FirstList, check if the name is present in our dictionary, and if so, combine the entry with the matching number:
result = [] for entry in FirstList: name = entry[0] if name in name_number_map: # Append the number from the dictionary to the original entry merged_entry = entry + [name_number_map[name]] result.append(merged_entry) print(result)
Shorter Version with List Comprehension
Once you get comfortable with list comprehensions (a handy Python shortcut), you can write this in one line:
result = [entry + [name_number_map[entry[0]]] for entry in FirstList if entry[0] in name_number_map]
Output
Both approaches will produce your desired result:
[['joe', '12-mar', 2101, 2524], ['mike', '13-mar', 2102, 2786]]
This method is efficient and easy to follow—perfect for someone getting started with Python. If you have questions about any part, feel free to ask!
内容的提问来源于stack exchange,提问作者Djordje pantovic

