How to create a list or tuple of empty lists in Python?

后端 未结 5 1702
不知归路
不知归路 2020-12-04 21:42

I need to incrementally fill a list or a tuple of lists. Something that looks like this:

result = []
firstTime = True
for i in range(x):
    for j in someLis         


        
5条回答
  •  萌比男神i
    2020-12-04 22:38

    Why not keep it simple by just appending the list in appropriate loop

    result = []
    for i in range(x):
        result.append([])
        for j in someListOfElements:
            result[i].append(j)
    

    [Edit: Adding example]

    >>> someListOfElements = ['a', 'b', 'c']
    >>> x = 3
    >>> result = []
    >>> for i in range(x):
    ...     result.append([])
    ...     for j in someListOfElements:
    ...         result[i].append(j)
    ... 
    >>> 
    >>> result
    [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
    

提交回复
热议问题