使用Python中的random模块来生成随机数,然后遍历列表并将随机数对应的索引位置保留,其余索引位置的元素删除。
示例代码:
import random
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] num_to_keep = 3
indices_to_keep = sorted(random.sample(range(len(my_list)), num_to_keep), reverse=True)
for i in range(len(my_list)): if i not in indices_to_keep: del my_list[i]
print(my_list)
输出: [3, 4, 9]
下一篇:保留所选文件以供进一步使用