用Python处理姓名与手机号列表:去重、空值处理及映射
Hey there! Let's fix up your code to get the exact output you want. First, let's go over what's not working with your current approach:
- Using
set()on both lists breaks the original pairing between names and phone numbers—sets are unordered, so when youzipthem later, you're just matching random values instead of the original pairs. - Your condition checks for
is None, but your empty values are empty strings (''), notNone, so those checks won't trigger at all. - You aren't handling the requirement to drop entries where only the name exists (no phone number), and the logic for filling names with phone numbers isn't hooked up right.
Here's a revised approach that addresses all your requirements:
phone = ['918222822','92929129','','92929129','','12345678','12345678','1727398',''] name = ['jhon', 'ele', '' , 'ele', '' , 'rock','rock','','burh'] # Step 1: Keep original name-phone pairs to preserve their correspondence pairs = list(zip(name, phone)) processed_pairs = [] for na, ph in pairs: # Skip entries where both name and phone are empty if na == '' and ph == '': continue # Use phone number as name if phone exists but name is empty if na == '' and ph != '': processed_pairs.append((ph, ph)) # Discard entries where name exists but no phone number elif na != '' and ph == '': continue # Add valid non-empty pairs else: processed_pairs.append((na, ph)) # Step 2: Remove duplicate pairs while keeping original order unique_pairs = list(dict.fromkeys(processed_pairs)) # Step 3: Print the final results for entry in unique_pairs: print(f"{entry[0]} {entry[1]}")
Let's break down what this does:
- Preserve original pairs: We start by zipping the original
nameandphonelists to keep each name linked to its corresponding phone number—no more random mismatches from using sets. - Filter and clean entries:
- Skip any entries where both name and phone are empty.
- If a phone number exists but the name is empty, we replace the name with the phone number (as per your desired output).
- If a name exists but there's no phone number, we discard that entry entirely.
- Remove duplicates: Using
dict.fromkeys()lets us deduplicate the pairs while keeping the order of their first occurrence (which matches your expected output order). - Print the final results: Loop through the unique, cleaned pairs and print them in the format you want.
When you run this code, you'll get exactly the output you're looking for:
jhon 918222822 ele 92929129 rock 12345678 1727398 1727398
内容的提问来源于stack exchange,提问作者user6476414
相关产品推荐
相关产品推荐

