通过乘法创建一个列表,但不要让每个列表都是mi

2024-07-03 08:09:34 发布

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

我有一个清单:

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)

Tags: informakelenifrangeresultstructure
2条回答

很难确切地理解您想要的是什么,但是我假设您想要创建一个独立元素的新列表。最简单的方法是使用deepcopy模块中的copy

from copy import deepcopy

newElemLines = [['1', '2', '5'], ['2', '9','3']]
translQuant = 3

# As for loop:
newElemLines2 = []
for _ in xrange(translQuant):
    newElemLines2.append(deepcopy(newElemLines))

# Or as list comprehension: 
newElemLines2 = [deepcopy(newElemLines) for _ in xrange(translQuant)]

Deepcopy确保您逐个元素复制所有内容,包括子列表

使用列表乘法:

newElemLines = [['1', '9', '1', '2'], ['2', '9', '2', '3'], ['3', '9', '3', '1'], ['4', '7', '4', '5', '6', '7', '8', '9', '10', '11']]

translQuant = 4

final_list = newElemLines*translQuant

使用列表理解:

newElemLines = [['1', '9', '1', '2'], ['2', '9', '2', '3'], ['3', '9', '3', '1'], ['4', '7', '4', '5', '6', '7', '8', '9', '10', '11']]

translQuant = 4
second_list = [[i] for i in newElemLines]
final_list = [second_list[0] for i in range(translQuant)]

相关问题 更多 >