You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用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 you zip them 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 (''), not None, 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:

  1. Preserve original pairs: We start by zipping the original name and phone lists to keep each name linked to its corresponding phone number—no more random mismatches from using sets.
  2. 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.
  3. Remove duplicates: Using dict.fromkeys() lets us deduplicate the pairs while keeping the order of their first occurrence (which matches your expected output order).
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:32:55