Creating a list in Python with multiple copies of a given object in a single line

前端 未结 6 1171
孤街浪徒
孤街浪徒 2020-12-03 04:56

Suppose I have a given Object (a string \"a\", a number - let\'s say 0, or a list [\'x\',\'y\'] )

I\'d like to create list containing many copies of thi

6条回答
  •  借酒劲吻你
    2020-12-03 05:17

    I hope this helps somebody. I wanted to add multiple copies of a dict into a list and came up with:

    >>> myDict = { "k1" : "v1" }
    >>> myNuList = [ myDict.copy() for i in range(6) ]
    >>> myNuList
    [{'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]
    >>> myNuList[1]['k1'] = 'v4'
    >>> myNuList
    [{'k1': 'v3'}, {'k1': 'v4'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}, {'k1': 'v3'}]
    

    I found that:

    >>> myNuList = [ myDict for i in range(6) ]
    

    Did not make fresh copies of the dict.

提交回复
热议问题