如何正确统计字符串中姓名元素的出现次数?
Hey there! I see where the issue is with your current code—you're converting the entire string into a list of individual characters, which is why Counter is counting things like apostrophes, numbers, and single letters instead of the actual names you care about. Let's fix this properly.
What's Wrong with the Original Approach?
When you run string_list = list(string), you're splitting the entire input string into every single character (like '[', '6', '7', etc.), not extracting the name elements embedded in the string. That's why your output is a count of each character, not the names you want to track.
The Correct Solution
Your input string is structured like multiple Python lists stuck together. We can safely parse this into a real Python list of lists, extract the names from each sub-list, then count those names with Counter. Here's how to do it:
from collections import Counter import ast # Your original input string string = "['673', 'andy', '05/05/16']['986', 'emma', '16/01/18']['147', 'david', '05/04/16']['996', 'nigel', '26/04/17']['209', 'emma', '04/03/17']['619', 'david', '18/07/18']['768', 'andy', '18/11/15']" # Step 1: Fix the string to be a valid list of lists (add commas between sub-lists) formatted_string = string.replace('][', '], [') # Step 2: Parse the formatted string into actual Python lists (safe with ast.literal_eval) parsed_data = ast.literal_eval(f"[{formatted_string}]") # Step 3: Extract all names (second element from each sub-list) names = [item[1] for item in parsed_data] # Step 4: Count name occurrences name_counts = Counter(names) # Step 5: Format output to match your desired result output = ' '.join([f"{name}: {count}" for name, count in name_counts.items()]) print(output)
Breakdown of Each Step:
- Fix the string format: The original string is missing commas between sub-lists. Replacing
']['with'], ['turns it into a valid list structure. - Safe parsing:
ast.literal_evalconverts the string into real Python lists without the security risks of using raweval(). - Extract names: We use a list comprehension to grab the second element (index 1) from each sub-list—this is always the name in your data.
- Count and format:
Counterhandles the duplicate counting, then we format the results into the exact string you're expecting.
Expected Output:
andy: 2 emma: 2 david: 2 nigel: 1
Quick Safety Note:
Why use ast.literal_eval instead of eval()? Because eval() will execute any code in the string, which is risky if your input comes from an untrusted source. ast.literal_eval only parses Python literals (lists, strings, numbers), so it's completely safe for this use case.
内容的提问来源于stack exchange,提问作者ladybug

