Python程序通过List中的Index元素计算功率
给定一个列表,任务是编写一个Python程序,通过其索引值计算每个元素的幂。
Input : test_list = [6, 9, 1, 8, 4, 7]
Output : [1, 9, 1, 512, 256, 16807]
Explanation : 8 * 8 * 8 = 512, as 8 is at 3rd index.
Input : test_list = [6, 9, 1, 8]
Output : [1, 9, 1, 512]
Explanation : 9**1 = 9, as 9 is at 1st index.
方法 1:使用**运算符+循环+ enumerate()
在这种情况下,获取功率的任务是使用 **运算符完成的,并且循环用于遍历元素。 enumerate() 用于获取索引和值。
Python3
# Python3 code to demonstrate working of
# Index Power List
# Using ** operator + loop + enumerate()
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
# printing original list
print("The original list is : " + str(test_list))
# ** does task of getting power
res = []
for idx, ele in enumerate(test_list):
res.append(ele ** idx)
# printing result
print("Powered elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Index Power List
# Using pow() + list comprehension + enumerate()
from math import pow
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
# printing original list
print("The original list is : " + str(test_list))
# pow() does task of getting power
# list comprehension for 1 liner alternative
res = [int(pow(ele, idx)) for idx, ele in enumerate(test_list)]
# printing result
print("Powered elements : " + str(res))
输出:
The original list is : [6, 9, 1, 8, 4, 7]
Powered elements : [1, 9, 1, 512, 256, 16807]
方法二:使用pow() +列表推导+ enumerate()
在这里,我们使用 pow() 执行获取功率的任务, enumerate() 用于获取带有值的索引。
蟒蛇3
# Python3 code to demonstrate working of
# Index Power List
# Using pow() + list comprehension + enumerate()
from math import pow
# initializing list
test_list = [6, 9, 1, 8, 4, 7]
# printing original list
print("The original list is : " + str(test_list))
# pow() does task of getting power
# list comprehension for 1 liner alternative
res = [int(pow(ele, idx)) for idx, ele in enumerate(test_list)]
# printing result
print("Powered elements : " + str(res))
输出:
The original list is : [6, 9, 1, 8, 4, 7]
Powered elements : [1, 9, 1, 512, 256, 16807]