📜  Python|列表的大小和元素求幂

📅  最后修改于: 2022-05-13 01:54:40.717000             🧑  作者: Mango

Python|列表的大小和元素求幂

有时,在使用Python列表时,我们可能会遇到需要以非常自定义的方式扩展列表的问题。我们可能不得不重复列表的内容,并且在这样做的同时,每次新列表必须是原始列表的幂。这种增量扩展在许多领域都有应用。让我们讨论一种可以执行此任务的方式。

方法:使用列表推导
此任务可以以粗略的方式执行,但使用列表推导式实现更短的实现总是更好。在此,我们分两步执行任务,首先我们制作一个辅助列表以形成一个指数因子列表,然后使用原始列表累积结果。

# Python3 code to demonstrate working of
# Size and element exponentiation of list
# Using list comprehension
  
# initializing list
test_list = [4, 5, 6]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Extension factor
N = 4
  
# Exponentiation factor 
M = 3
  
# Size and element exponentiation of list
# Using list comprehension
temp = [1 * M**i for i in range(N)]
res = list([ele ** tele for tele in temp for ele in test_list])
  
# printing result 
print("List after extension and exponentiation : " + str(res))
输出 :
The original list is : [4, 5, 6]
List after extension and exponentiation : [4, 5, 6, 64, 125, 216, 262144, 1953125, 10077696, 18014398509481984, 7450580596923828125, 1023490369077469249536]