用‘N’替換前‘K’個元素的 Python 程式
當需要用‘N’替換前‘K’個元素時,採用了一個簡單的迭代。
示例
以下展示了此方法示例:
my_list = [13, 34, 26, 58, 14, 32, 16, 89]
print("The list is :")
print(my_list)
K = 2
print("The value of K is :")
print(K)
N = 99
print("The value of N is :")
print(N)
for index in range(K):
my_list[index] = N
print("The result is :")
print(my_list)輸出
The list is : [13, 34, 26, 58, 14, 32, 16, 89] The value of K is : 2 The value of N is : 99 The result is : [99, 99, 26, 58, 14, 32, 16, 89]
解釋
定義了一個整數列表,並顯示在控制檯中。
定義了‘K’和‘N’的值,並顯示在控制檯中。
迭代‘K’範圍內的序列,並將索引中的每個元素指定為 N 的值。
此操作最多執行到索引‘K’中的值。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP