python - 在Python中随机生成二维列表

我正在尝试生成 5x5 列表,其中正好有 10 个放置在 2D 列表的随机位置。

我想让其余的条目都为零。我怎样才能做到?

import random

def randomNumbers():

    mylist=[random.randint(0, 1) for _ in range(5)]
    return mylist

最佳答案

你可以这样做

from random import shuffle
def randomNumbers():
    l=[1 for _ in range(10)]+[0 for _ in range(15)]
    shuffle(l)
    lst=[]
    for i in range(0,25,5):
        lst.append(l[i:i+5])
    return lst

https://stackoverflow.com/questions/64874387/

相关文章:

python - Windows 上的 Gcloud 命令(使用 git bash)正在记录错误 :

c - 打印函数,C语言的hello world

react-native - React native 每次打开页面时如何执行函数

azure-devops - Azure Devops - Terraform 任务失败并出现错误

vue.js - 如何制作可点击的带有悬停效果的q卡?

javascript - 在 React Native 中安排本地通知不起作用

scala - scala中以下两种模式匹配案例有什么区别

node.js - docker-compose npm install && npm start

c++ - 仅当使用 unordered_map 而不是 vector 时,将 const 作为此参

wordpress - Disqus iframe 透明度不适用于 Chrome 87