Python——隨機插入元素 K 次


當需要隨機插入元素 K 次時,將使用“random”軟體包以及“random”軟體包中的方法,外加簡單的迭代。

示例

以下對此進行演示:

import random

my_list = [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90]

print("The list is : " )
print(my_list)

print("The list after sorting is : " )
my_list.sort()
print(my_list)

to_add_list = ["Python", "Object", "oriented", "language", 'cool']

K = 3
print("The value of K is ")
print(K)

for element in range(K):
   index = random.randint(0, len(my_list))
   my_list = my_list[:index] + [random.choice(to_add_list)] + my_list[index:]

print("The resultant list is : ")
print(my_list)

輸出

The list is :
[34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90]
The list after sorting is :
[0, 3, 8, 9, 11, 12, 21, 34, 41, 56, 90]
The value of K is
3
The resultant list is :
[0, 3, 8, 9, 11, 12, 'Python', 21, 34, 41, 56, 90, 'Object', 'oriented']

說明

  • 將必需的軟體包匯入到環境中。

  • 定義一個整數列表,並顯示在控制檯上。

  • 使用“sort”方法對其進行排序,並再次顯示在控制檯上。

  • 定義 K 的值,並顯示在控制檯上。

  • 對 K 的值進行迭代,並使用“random”軟體包中的“randint”生成索引的元素。

  • 使用列表索引和“random”軟體包中的“choice”方法使用連線運算子將值新增到列表中。

  • 此列表以輸出形式顯示在控制檯上。

更新時間:13-Sep-2021

248 次瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.