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']
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
说明
将必需的软件包导入到环境中。
定义一个整数列表,并显示在控制台上。
使用“sort”方法对其进行排序,并再次显示在控制台上。
定义 K 的值,并显示在控制台上。
对 K 的值进行迭代,并使用“random”软件包中的“randint”生成索引的元素。
使用列表索引和“random”软件包中的“choice”方法使用连接运算符将值添加到列表中。
此列表以输出形式显示在控制台上。
广告