Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python3.4中,从2D列表的每一行中选择一个随机数_Python_Python 3.x - Fatal编程技术网

在python3.4中,从2D列表的每一行中选择一个随机数

在python3.4中,从2D列表的每一行中选择一个随机数,python,python-3.x,Python,Python 3.x,在项目中,我有如下列表: a = [[0, 1, 2, 3], [1, 2, 3], [0, 2, 3], [1, 2]] 我想从每行中选择一个数字,这是该行列的索引。示例:如果我们从第一行选择0,从第二行选择2,从第三行选择0,从第四行选择1,则输出如下 [['1', '0', '0', '0'], ['0', '0', '1', '0'], ['1', '0', '0', '0'], ['0', '1', '0', '0']] 1 0 0 0 0 0 1 0 1 0 0

在项目中,我有如下列表:

a = [[0, 1, 2, 3], [1, 2, 3], [0, 2, 3], [1, 2]]     
我想从每行中选择一个数字,这是该行列的索引。示例:如果我们从第一行选择0,从第二行选择2,从第三行选择0,从第四行选择1,则输出如下

[['1', '0', '0', '0'], ['0', '0', '1', '0'], ['1', '0', '0', '0'], ['0', '1', '0', '0']]

1 0 0 0  
0 0 1 0  
1 0 0 0  
0 1 0 0 
我的工作如下

for i in range(0,len(a)): 
    print(random.choice(a))
但它会打印其中一个子列表。

这就是您想要的:

a = [[0, 1, 2, 3], [1, 2, 3], [0, 2, 3], [1, 2]]  
for x in a:
    b=[0,0,0,0]
    if x:
        b[x.index(random.choice(x))]=1
        print b
    else:print b

是,
随机。选择(a)
将选择一个子列表。你是说a:print(random.choice(sublist))中的子列表是
?是的,每个子列表都有一个随机数,甚至是
random.choice(a[i])
为什么a=[[0,1,2,3],[1,2,3],[0,2,3],][]如何处理…我是python新手本例索引将超出范围错误,因为最后一个子列表为空。因此,如果您的列表有空的子列表,您需要通过conditiona=[[],[1,2,3],[0,2,3],[1,2]]来检查它。对于这一点,我希望得到相同的结果,就像来自2,3,4行的随机数一样,第一行应该都是0,因为第一个子列表是空的,所以您将得到相同的错误。您能告诉我那个条件是什么吗。。。?