我有一个清单:
newElemLines = [['1', '2', '5'], ['2', '9','3']]
我希望它看起来像这样:
newElemLines2 = [[['1', '2', '5'], ['2', '9', '3']], [['1', '2', '5'], ['2', '9', '3']], [['1', '2', '5'], ['2', '9', '3']]]
所以我想我可以用这个代码:
newElemLines = [['1', '2', '5'], ['2', '9','3']]
translQuant = 3
newElemLines = [newElemLines]*(translQuant)
nodeQuant = 11
for i in range(0, len(newElemLines)):
for j in range(0, len(newElemLines[i])):
for x in range(0, len(newElemLines[i][j])):
newElemLines[i][j][x] = int(newElemLines[i][j][x]) + int((i)*nodeQuant)
print(newElemLines)
然而,我所乘的原始列表只是镜像了列表中所有4个部分的这一行:
newElemLines[i][j][x] = int(newElemLines[i][j][x]) + int((i)*nodeQuant)
KFL也有同样的问题: Create a list utilizing multiplication but not have each list mirror 所以我试着用这样的方法,但仍然不起作用
newElemLines = [['1', '2', '5'], ['2', '9','3']]
nodeQuant = 11
def make_structure(dims, fill=None):
fill = False if fill is None else fill
get_fill = lambda: fill() if callable(fill) else fill
global result
result = []
for i in range(dims[0]):
if len(dims) > 1:
result.append(make_structure(dims[1:], fill=fill))
else:
result.append(get_fill())
print(result)
fill = newElemLines
dims = [3]
make_structure(dims, fill)
newElemLines = result
for i in range(0, len(newElemLines)):
for j in range(0, len(newElemLines[i])):
for x in range(0, len(newElemLines[i][j])):
newElemLines[i][j][x] = int(newElemLines[i][j][x]) + int((i)*nodeQuant)
print(newElemLines)
很难确切地理解您想要的是什么,但是我假设您想要创建一个独立元素的新列表。最简单的方法是使用
deepcopy
模块中的copy
:Deepcopy确保您逐个元素复制所有内容,包括子列表
使用列表乘法:
使用列表理解:
相关问题 更多 >
编程相关推荐