在保持原始列表形状的情况下增加列表列表中的每个元素
Increment of every element in list of lists with keeping the shape of the original list
我有一个列表,例如:[[1,2,3],[2,4],[3,5],[4,6,7]]
我想重复十次列表,每个元素都比前一个元素增加 1,例如:[[1,2,3],[2,4],[3,5],[4,6,7],[2,3,4],[3,5],[4,6],[5,7,8]................40 elements(lists)]
您可以使用嵌套列表理解来做到这一点:
>>> a = [[1,2,3],[2,4],[3,5],[4,6,7]]
>>> [[y+i for y in x] for i in range(10) for x in a]
[[1, 2, 3], [2, 4], [3, 5], [4, 6, 7], [2, 3, 4], [3, 5], [4, 6], [5, 7, 8], [3, 4, 5], [4, 6], [5, 7], [6, 8, 9], [4, 5, 6], [5, 7], [6, 8], [7, 9, 10], [5, 6, 7], [6, 8], [7, 9], [8, 10, 11], [6, 7, 8], [7, 9], [8, 10], [9, 11, 12], [7, 8, 9], [8, 10], [9, 11], [10, 12, 13], [8, 9, 10], [9, 11], [10, 12], [11, 13, 14], [9, 10, 11], [10, 12], [11, 13], [12, 14, 15], [10, 11, 12], [11, 13], [12, 14], [13, 15, 16]]
最外层的迭代是 for i in range(10)
,它将带您遍历 i
的十个值,这些值将添加到 a
的元素中。下一级 for x in a
将 a
的元素迭代为 x
。内部列表理解 [y+i for y in x]
是将每个 x
增加 i
。
我有一个列表,例如:[[1,2,3],[2,4],[3,5],[4,6,7]]
我想重复十次列表,每个元素都比前一个元素增加 1,例如:[[1,2,3],[2,4],[3,5],[4,6,7],[2,3,4],[3,5],[4,6],[5,7,8]................40 elements(lists)]
您可以使用嵌套列表理解来做到这一点:
>>> a = [[1,2,3],[2,4],[3,5],[4,6,7]]
>>> [[y+i for y in x] for i in range(10) for x in a]
[[1, 2, 3], [2, 4], [3, 5], [4, 6, 7], [2, 3, 4], [3, 5], [4, 6], [5, 7, 8], [3, 4, 5], [4, 6], [5, 7], [6, 8, 9], [4, 5, 6], [5, 7], [6, 8], [7, 9, 10], [5, 6, 7], [6, 8], [7, 9], [8, 10, 11], [6, 7, 8], [7, 9], [8, 10], [9, 11, 12], [7, 8, 9], [8, 10], [9, 11], [10, 12, 13], [8, 9, 10], [9, 11], [10, 12], [11, 13, 14], [9, 10, 11], [10, 12], [11, 13], [12, 14, 15], [10, 11, 12], [11, 13], [12, 14], [13, 15, 16]]
最外层的迭代是 for i in range(10)
,它将带您遍历 i
的十个值,这些值将添加到 a
的元素中。下一级 for x in a
将 a
的元素迭代为 x
。内部列表理解 [y+i for y in x]
是将每个 x
增加 i
。