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

如何生成列表中所有无序数对的整数均值组成的列表?

Alright, let's work through this problem to generate list b from list a as specified. Here's a clear breakdown and solution:

Problem Breakdown

First, let's restate the requirements to make sure we're on the same page:

  • We need to create unordered pairs from the input list a—so (x,y) counts as the same pair as (y,x), and we only process each unique pair once.
  • For each pair, calculate the mean. We only keep this mean in list b if it's an integer.
  • Duplicate elements in a form valid pairs (like (0,0) when there are two 0s in a), and these pairs need to be included in our calculations.
Approach

To solve this correctly, follow these steps:

  1. Iterate over unordered pairs only: Use nested loops where the inner loop starts at the index of the outer loop's element (inclusive). This ensures we don't repeat pairs like (x,y) and (y,x), but still capture pairs of the same element when duplicates exist.
  2. Check for integer mean: For each pair (x, y), first check if their sum is even—because only then will their mean be an integer. If it is, compute the mean and add it to b.
  3. Collect all valid results: Gather every valid integer mean into the final list b.
Code Example (Python)

Let's test this approach with the sample input provided:

a = [0, 0, 3, 4, 1, 2, 9]
b = []

# Loop through all unordered pairs (i <= j to avoid duplicate pair processing)
for i in range(len(a)):
    for j in range(i, len(a)):
        x = a[i]
        y = a[j]
        total = x + y
        # Only keep the mean if it's an integer
        if total % 2 == 0:
            mean = total // 2
            b.append(mean)

print(b)  # Output: [0, 2, 1, 2, 1, 2, 6, 3, 5]
Verifying the Sample Output

Let's cross-check the sample to confirm the code works as expected:

  • Valid pairs and their means:
    • (0,0) → 0 ✔️
    • (0,4) → 2 ✔️
    • (0,2) → 1 ✔️
    • (second 0,4) → 2 ✔️
    • (second 0,2) → 1 ✔️
    • (3,1) → 2 ✔️
    • (3,9) → 6 ✔️
    • (4,2) → 3 ✔️
    • (1,9) → 5 ✔️
  • Collecting these gives exactly the sample b list provided.

内容的提问来源于stack exchange,提问作者gunjanpatait

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:54:05