Create list of single item repeated N times

前端 未结 6 1117
南笙
南笙 2020-11-22 03:57

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = len

6条回答
  •  盖世英雄少女心
    2020-11-22 04:51

    Create List of Single Item Repeated n Times in Python

    Immutable items

    For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:

    [e] * 4
    

    Note that this is best only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.

    schema = ['string'] * len(columns)
    

    Mutable items

    I've used Python for a long time now, and I have never seen a use-case where I would do the above with a mutable instance. Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:

    list_of_lists = [[] for _ in columns]
    

    The underscore is simply a throwaway variable name in this context.

    If you only have the number, that would be:

    list_of_lists = [[] for _ in range(4)]
    

    The _ is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.


    Caveats for using the immutable method with mutable items:

    Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

    foo = [[]] * 4
    foo[0].append('x')
    

    foo now returns:

    [['x'], ['x'], ['x'], ['x']]
    

    But with immutable objects, you can make it work because you change the reference, not the object:

    >>> l = [0] * 4
    >>> l[0] += 1
    >>> l
    [1, 0, 0, 0]
    
    >>> l = [frozenset()] * 4
    >>> l[0] |= set('abc')
    >>> l
    [frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]
    

    But again, mutable objects are no good for this, because in-place operations change the object, not the reference:

    l = [set()] * 4
    >>> l[0] |= set('abc')    
    >>> l
    [set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]
    

提交回复
热议问题