创建列表列表。修改列表中的元素

时间:2016-11-25 18:37:01

标签: python list python-3.x for-loop matrix

要求:

定义函数createMatDimXDim(dim) 此函数接收大于或等于2的正整数,并返回维度为dim x dim的方阵,其中的内容是等于行号乘以10加上列号的数字。

预期产出:

print (createMatDimXDim (4)) 
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

我的代码:

def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for i in range(dim):
           lis[i].append(int(lis[i][0])+1)
    return lis

我的代码输出:

[[0, 1, 1, 1, 1], [10, 1, 11, 11, 11], [20, 1, 1, 21, 21], [30, 1, 1, 1, 31]]

我想这样做:

lis[i].append(int(lis[i][i-1])+1)

但它给了我一个IndexError

4 个答案:

答案 0 :(得分:4)

def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for j in range(dim-1):               # for the nested loop you need to use a new 
                                             # variable j
           lis[i].append(int(lis[i][j])+1)
    return lis

createMatDimXDim(4)
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

列表理解的另一个选项:

dim = 4
[[i * 10 + j for j in range(dim)] for i in range(dim)]
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

答案 1 :(得分:3)

def createMatDimXDim(dim):
    return [[j for j in range(i*10, i*10+dim)] for i in range(dim)]

答案 2 :(得分:2)

您可以使用2D列表理解。

def createMatDimXDim(dim):
    return [[j for j in range(i*10, i*10+dim)] for i in range(dim)]
createMatDimXDim(4)

输出:

[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

答案 3 :(得分:1)

一个容易理解的方法是:

public class MyFragment extends Fragment {
    public MyFragment() {
    }

    public MyFragment(String name) {
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_KEY_NAME, name);
        setArguments(bundle);
    }
}

public class MyFragment extends Fragment {
    public MyFragment() {
    }

    public static MyFragment newInstance(String name) {
        MyFragment myFragment = new MyFragment();
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_KEY_NAME, name);
        myFragment.setArguments(bundle);
        return myFragment;
    }
}

输出:

def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for j in range(dim-1):                                    
           lis[i].append(int(lis[i][j])+1)
    return lis

createMatDimXDim(4)