Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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
Python 如何创建列表列表,其中每个子列表';增量';如下:[1,0,0],[1,1,0],[1,1,1]_Python_List - Fatal编程技术网

Python 如何创建列表列表,其中每个子列表';增量';如下:[1,0,0],[1,1,0],[1,1,1]

Python 如何创建列表列表,其中每个子列表';增量';如下:[1,0,0],[1,1,0],[1,1,1],python,list,Python,List,这是可行的,但很笨拙,也不是很“Pythonic”。我也希望能够运行不同的“numValues”值,比如4到40 innerList = [] outerList = [] numValues = 12 loopIter = 0 for i in range(numValues): innerList.append(0) for i in range(numValues): copyInnerList = innerList.copy() outerList.appe

这是可行的,但很笨拙,也不是很“Pythonic”。我也希望能够运行不同的“numValues”值,比如4到40

innerList = []
outerList = []
numValues = 12
loopIter = 0

for i in range(numValues):
    innerList.append(0)

for i in range(numValues):
    copyInnerList = innerList.copy()
    outerList.append(copyInnerList)

for i in range(len(innerList)):
    for j in range(loopIter + 1):
        outerList[i][j] = 1
    loopIter += 1

print(outerList)

您可以通过嵌套列表理解来实现这一点,在
范围(numValues)
上使用两个迭代器,并且只有在第二个迭代器为
时才设置
1
,一个有用的功能是将列表相乘

>[1]*3
[1, 1, 1]
您可以将其放入for循环并添加所需的0。
你可以想象这样的函数

def子列表(编号:int)->列表:
"""
创建增加1的子列表
"""
结果=[]
对于范围内的i(编号):
子列表=[1]*(i+1)+[0]*(数字-i-1)
结果追加(子列表)
返回结果
然后可以调用该函数

>>子列表(4)
[[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]

如果numpy是一个选项,则可以通过以下方法轻松实现:


我认为在numpy中使用矩阵方法更直观一些

numValues = 5
my_array = np.eye(numValues)
结果是

array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])
从这个矩阵中,您可以看到,您需要做的唯一一件事就是对行求和

sol =  [np.sum(mat[:i], axis=0) for i in range(numValues+1)][1:]
你得到了什么

 [array([1., 0., 0., 0., 0.]),
 array([1., 1., 0., 0., 0.]),
 array([1., 1., 1., 0., 0.]),
 array([1., 1., 1., 1., 0.]),
 array([1., 1., 1., 1., 1.])]

您好,如果您的代码工作正常,并且您要求改进,这不是合适的地方,您应该发布它CodeReview:OK-谢谢@Romaill。下次我会用的。
numValues = 5
my_array = np.eye(numValues)
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])
sol =  [np.sum(mat[:i], axis=0) for i in range(numValues+1)][1:]
 [array([1., 0., 0., 0., 0.]),
 array([1., 1., 0., 0., 0.]),
 array([1., 1., 1., 0., 0.]),
 array([1., 1., 1., 1., 0.]),
 array([1., 1., 1., 1., 1.])]