Python程序用给定的数字替换范围内的列表元素
给定一个范围,这里的任务是编写一个Python程序,该程序可以用指定的数字更新落在给定索引范围内的列表元素。
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9
Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1]
Explanation : List is updated with 9 from 4th to 8th index.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 8
Output : [4, 6, 8, 1, 8, 8, 8, 8, 12, 3, 9, 1]
Explanation : List is updated with 8 from 4th to 8th index.
方法 1:使用切片和*运算符
在这里,我们使用切片执行获取范围元素的任务,*运算符用于执行更新并提供所需的元素来填充更新。
程序:
Python3
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# initializing K
K = 9
# getting range using slicing and
# required elements using * operator
test_list[i:j] = [K] * (j - i)
# printing result
print("Range Updated list : " + str(test_list))
Python3
from itertools import repeat
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# initializing K
K = 9
# getting range using slicing and
# required elements using repeat()
test_list[i:j] = repeat(K, (j - i))
# printing result
print("Range Updated list : " + str(test_list))
输出:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9]
方法 2:使用repeat()和列表切片
类似的任务也可以使用 repeat() 来执行,它使用未构建的构造来获取所需的元素。
程序:
蟒蛇3
from itertools import repeat
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# initializing K
K = 9
# getting range using slicing and
# required elements using repeat()
test_list[i:j] = repeat(K, (j - i))
# printing result
print("Range Updated list : " + str(test_list))
输出:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9]