How to create tuple with a loop in python

后端 未结 6 1286
梦如初夏
梦如初夏 2021-02-13 17:24

I want to create this tuple:

a=(1,1,1),(2,2,2),(3,3,3),(4,4,4),(5,5,5),(6,6,6),(7,7,7),(8,8,8),(9,9,9)

I tried with this

a=1,1,         


        
6条回答
  •  我在风中等你
    2021-02-13 18:00

    itertools.repeat can also be used here:

    >>> from itertools import repeat
    >>> [tuple(repeat(i, 3)) for i in range(1, 10)]
    [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9)]
    

    If you want the final result to be in a tuple of tuples instead of a list of tuples, you can wrap tuple again:

    >>> tuple(tuple(repeat(i, 3)) for i in range(1, 10))
    ((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9))
    

提交回复
热议问题