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

如何将列表中的每个元素提升至其对应索引的幂次?

Got it, let's solve this problem where we need to transform an input array by raising each element to the power of its index position (starting from 0). Here's how you can approach it in a couple of common programming languages:

Python Solution

You can use a clean list comprehension paired with enumerate()—this function lets you loop through the array while keeping track of both each element and its index.

def transform_array(arr):
    return [element ** index for index, element in enumerate(arr)]

# Test with your examples
print(transform_array([3, 2, 5]))  # Output: [1, 2, 25]
print(transform_array([5, 10, 20])) # Output: [1, 10, 400]

How it works

  • enumerate(arr) generates pairs like (0, 3), (1, 2), (2, 5) for the first test case.
  • For each pair, we calculate element ** index (element raised to the index power). Since any number to the 0th power is 1, the first element will always be 1—perfect for your required output.

JavaScript Solution

In JavaScript, the map() method is ideal here. It lets you iterate over the array and modify each element using its index directly.

function transformArray(arr) {
    return arr.map((element, index) => Math.pow(element, index));
}

// Test the examples
console.log(transformArray([3, 2, 5]));  // Output: [1, 2, 25]
console.log(transformArray([5, 10, 20])); // Output: [1, 10, 400]

How it works

  • The map() callback receives both the current element and its index.
  • Math.pow(element, index) handles the exponent calculation exactly as needed. Just like in Python, this will return 1 for the first element (since index 0 makes any non-zero number to the 0th power 1).

Quick Edge Case Note

If your input might have 0 as the first element, keep in mind that 0^0 is mathematically undefined, but most languages (including Python and JS) return 1 for this scenario, which matches your example pattern. If you need to handle this case differently, you can add a simple conditional check in the function.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:17:36