如何在二维数组中的给定位置插入元素,从列表中获取这些元素[Python3]

2024-04-26 04:48:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是:

words =['a','b','c','d']
table = [['','','']['','','']['','','']['','','']]

我想获得的[可能不使用numpy库]:

table = [['a','','']['b','','']['c','','']['d','','']]

我是如何做到的:

#a
for row in range(4):
    for word in words:
        table[row][0] = [w for w in words]

[output]
[['a', 'b', 'c', 'd'], '', ''],
[['a', 'b', 'c', 'd'], '', ''],
[['a', 'b', 'c', 'd'], '', ''],
[['a', 'b', 'c', 'd'], '', '']]

#b
for row in range(4):
    for word in words:
        table[row][0] = word

[output]
[['a', '', ''],
 ['a', '', ''],
 ['a', '', ''],
 ['a', '', '']]

#c
for row in range(4):
    table[row][0] = [word for w in words]

[output]
[['a', 'a', 'a', 'a'], '', ''],
[['a', 'a', 'a', 'a'], '', ''],
[['a', 'a', 'a', 'a'], '', ''],
[['a', 'a', 'a', 'a'], '', '']]

有没有办法不用numpy图书馆? 还是用numpy图书馆更好? 我也试过了表.append(word)但是没有得到正确的输出。你知道吗


Tags: innumpyforoutput图书馆tablerangeword
2条回答

你可以使用一个简单的列表:

words = ['a','b','c','d']

table = [[i, '', ''] for i in words]

# [['a', '', ''], ['b', '', ''], ['c', '', ''], ['d', '', '']]

你可以试试这是:-

words =  ['a','b','c','d']
table = [['','',''],['','',''],['','',''],['','','']]
ls = [list(x)+y[1:] for x,y in zip(words,table)]
print(ls)

输出

[['a', '', ''], ['b', '', ''], ['c', '', ''], ['d', '', '']]

相关问题 更多 >