📌  相关文章
📜  用“N”替换第一个“K”元素的Python程序

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

用“N”替换第一个“K”元素的Python程序

给定一个 List,用 N 替换前 K 个元素。

方法一:使用循环

这种朴素的方法迭代列表“ k ”次数并将“ N ”分配给遇到的每个元素,直到循环结束。

Python3
# initializing list
test_list = [3, 4, 6, 8, 4, 2, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# initializing N
N = 6
  
# assigning value 'N' till K elements
for idx in range(K):
  
    test_list[idx] = N
  
# printing result
print("Elements after replacement : " + str(test_list))


Python3
# initializing list
test_list = [3, 4, 6, 8, 4, 2, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# initializing N
N = 6
  
# assigning the N value till K elements
test_list[: K] = [N] * K
  
# printing result
print("Elements after replacement : " + str(test_list))


输出
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]


方法二:使用列表切片

在这里,我们只从列表中切出几个元素,并将“ N ”分配给切片列表。

蟒蛇3

# initializing list
test_list = [3, 4, 6, 8, 4, 2, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# initializing N
N = 6
  
# assigning the N value till K elements
test_list[: K] = [N] * K
  
# printing result
print("Elements after replacement : " + str(test_list))
输出
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]