简体   繁体   English

嵌套列表及其索引调用

[英]Nested Lists and their index calls

I was wondering how I would go about assigning a value to a specific index in a list that is inside another list. 我想知道如何为另一个列表内的列表中的特定索引分配值。 For example: 例如:

For a list parentList 对于列表parentList

for i in range(0,rows, 1):
        parentList[i] = []
        for j in range(0,cols,1):
            parentList[i[j]] = 0

Not sure if that is even the right syntax for assignment like this. 不知道这是否就是这样的正确语法。

I know I can do .append, but what I need to do for my problem is create a sparse matrix, so everything should be 0 except for the values that the user specifies in the form (row) (col) (value) . 我知道我可以添加.append,但是我需要解决的问题是创建一个稀疏矩阵,因此除用户以(row) (col) (value)形式指定的值之外,其他所有值都应为0。

So I thought using the indexes of the lists would help with assignment. 因此,我认为使用列表的索引将有助于分配。 If there is a better way, please let me know! 如果有更好的方法,请告诉我!

EDIT: This is an example of what is being done 编辑:这是正在完成的示例

input: 输入:

1 2 2

1 3 3

2 1 4

3 3 5

0 0 0


1 3 7

2 2 8

3 2 9

3 3 6

0 0 0

The first matrix in the input is: 输入中的第一个矩阵是:

0 2 3

4 0 0

0 0 5

The second matrix is: 第二个矩阵是:

0 0 7

0 8 0

0 9 6

Their product is: 他们的产品是:

0 43 18

0 0 28

0 45 30

So the output should be: 因此输出应为:

1 2 43

1 3 18

2 3 28

3 2 45

3 3 30

0 0 0

I have to use a 1D array of linked lists to represent this in my code and all input and output is done through the Python Shell. 我必须使用一维链接列表数组来在我的代码中表示这一点,并且所有输入和输出都是通过Python Shell完成的。

It is easy to work with numpy arrays: 使用numpy数组很容易:

import numpy as np
a=np.empty((3,3))
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        a[i][j]=0
>>> a
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

Python lists aren't sparse - but there are other packages like numpy and scipy that provide them. Python列表并不稀疏-但是还有其他一些软件包(例如numpy和scipy)提供了它们。 If your dataset isn't that big and you are okay just prefilling a list, this will do it: 如果您的数据集不那么大而您可以预填充一个列表,则可以这样做:

rows = 100
cols = 13
l = [[0]*cols for _ in rows]

The [0]*cols creates an inner list filled with zeros, and [[0]*cols for _ in rows] repeats that operation for the number of rows you want. [0]*cols创建一个内部列表,该列表用零填充, [[0]*cols for _ in rows]对所需的行数重复该操作。

After that, you address individual cells like 之后,您要对单个单元格进行寻址

l[2][3] = 111

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM