Python – 从 K 值获取下 N 个元素


当需要从 K 值获取下 N 个元素时,使用简单的迭代方法。

以下是对其的演示 -

示例

Open Compiler
my_list = [31, 24, 46, 18, 34, 52, 26, 29] print("The list is :") print(my_list) K = 2 print("The value of K is :") print(K) N = 3 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 :
[31, 24, 46, 18, 34, 52, 26, 29]
The value of K is :
2
The value of N is :
3
The result is :
[3, 3, 46, 18, 34, 52, 26, 29]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 定义一个列表并在控制台中显示。

  • 定义 K 和 N 的值,并在控制台中显示。

  • 在 K 范围内遍历列表,并将 N 的值赋予特定索引处的元素。

  • 这是显示在控制台中输出。

更新于:08-Sep-2021

215 次浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告