随机更改为python中零列表的1 p元素

时间:2018-03-03 07:06:29

标签: python

我有一个大小为m的零列表。我想随机选择p索引并将其更改为1。

Y = [0 for x in range(M)]

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

import random

x = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

x = [1 if bool(random.getrandbits(1)) else 0 for i in x]

print(x) # [1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1]

- 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 - 〜 -

import random

leninp = int(input("len"))

raninp = int(input("random"))

x = [0 for i in range(leninp-raninp)] + [1 for i in range(raninp)]

random.shuffle(x)

print(x)