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

如何编写代码实现嵌套列表间指定元素的除法运算?

Solution for Generating the Target Nested List

Got it, let's work through this problem to build your desired list3. The core idea is to map each m value in list2 (excluding the first string element) to the corresponding y value from list1 and compute their division.

Step-by-Step Explanation

  1. Extract Y Values First: Pull all the second elements from list1 into a separate list—this makes it easy to reference the correct y value for each m later, without repeatedly indexing into list1.
  2. Process Each Sublist in List2: For every sublist in list2, keep the first string element, then calculate m/y for each subsequent m using the matching y from our extracted list.

Python Code Implementation

Option 1: Readable Loop Version

Great for debugging or if you need to add extra logic (like handling zero values):

# Sample input data (replace with your actual values)
list1 = [[10, 2], [20, 5], [30, 10]]
list2 = [["z1", 4, 10, 30], ["z2", 6, 15, 40], ["z3", 8, 20, 50]]

# Extract all y values from list1
y_values = [y for _, y in list1]

list3 = []
for sublist in list2:
    # Start with the first string element
    new_entry = [sublist[0]]
    # Calculate m/y for each pair of m and corresponding y
    for m, y in zip(sublist[1:], y_values):
        # Add a check here if you need to handle y=0 cases
        new_entry.append(m / y)
    list3.append(new_entry)

print(list3)
# Output: [['z1', 2.0, 2.0, 3.0], ['z2', 3.0, 3.0, 4.0], ['z3', 4.0, 4.0, 5.0]]

Option 2: Concise List Comprehension

Perfect for a clean, Pythonic one-liner once you're confident in the logic:

y_values = [y for _, y in list1]
list3 = [[sublist[0]] + [m/y for m, y in zip(sublist[1:], y_values)] for sublist in list2]

Notes

  • Zero Division Handling: If there's a chance any y value could be 0, modify the division line to handle it gracefully, e.g.:
    new_entry.append(m / y if y != 0 else 0)  # Or use NaN, None, or a custom placeholder
    
  • Data Types: Ensure your m and y values are numeric (int/float) to avoid type errors when performing division.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:19:32