假设我们有一个列表l = [0,3,2]
。我希望以随机方式使用相同的值扩展它,因此l = [0,3,2,2,0]
答案 0 :(得分:1)
考虑这样的事情:
create table my_table(id serial primary key, user_name text unique);
insert into my_table (user_name) values
('John'), ('Ben'), ('Alice'), ('John'), ('Ben'), ('Alice'), ('Sam')
on conflict do nothing;
select *
from my_table;
id | user_name
----+-----------
1 | John
2 | Ben
3 | Alice
7 | Sam
(4 rows)
答案 1 :(得分:1)
您可以使用random
模块中的函数生成额外元素:
/**
* Collects all `name` property values recursively
*
* @param o an object
* @param res the resulting array
* @returns {*|Array}
*/
function getAllNames(o, res) {
var names = res || [];
for (var k in o) {
if (k === 'name') {
names.push(o[k]); // saving `name` value
} else if(k === 'child' && typeof o[k] === 'object') {
getAllNames(o[k], names); // processing nested `child` object
}
}
return names;
}
var obj = {
name:'one',
child:{
name:'two',
child:{
name:'three',
child: {
name: 'four',
child: {
name: 'five'
}
}
}
}
};
console.log(getAllNames(obj, []));
然后使用>>> import random
>>> lst, n = [0, 3, 2], 2
>>> [random.choice(lst) for _ in range(n)]
[0, 2]
>>> random.choices(lst, k=n) # Python 3.6+
[3, 0]
将元素添加到列表中。
答案 2 :(得分:0)
如果我们想在随机索引处插入随机数,我们可以使用list 的插入函数。
>>> import random
>>> l = [0,3,2]
>>> n = 10
>>> for i in range(2,n):
l.insert(random.randrange(i),random.randrange(i))
>>> print l
[0, 3, 0, 0, 2, 0, 3, 2, 5, 3, 2]