How do you create a list of repeated tuples in Python?

前端 未结 2 1085
旧时难觅i
旧时难觅i 2021-01-29 14:13

Say I have a list of tuples, I extract the first tuple from this list and then want to create a new list that simply takes the first tuple and repeats it n times creating a list

2条回答
  •  逝去的感伤
    2021-01-29 14:29

    Let say that you have a list like this one:

    list_of_tuples = [('foo', 'bar'), ('baz', 'qux')]
    

    If you want to repeat the first tuple n times, you can use itertools.repeat

    import itertools
    itertools.repeat(list_of_tuples[0], n)
    

    where n is the number of times you want the first tuple to be repeated. itertools.repeat will return a generator.

提交回复
热议问题