Unpack list into middle of a tuple

前端 未结 3 1948
一整个雨季
一整个雨季 2020-12-19 03:45

I have a list of uncertain size:

l = [...]

And I want to unpack this list into a tuple that has other values, but the below fails:

相关标签:
3条回答
  • 2020-12-19 03:54

    You cannot unpack into a tuple by substituting values like that (yet - see PEP 448), because unpacking will happen only on the left hand side expression or as the error message says, assignment target.

    Also, assignment target should have valid Python variables. In your case you have string literals also in the tuple.

    But you can construct the tuple you wanted, by concatenating three tuples, like this

    >>> l = [1, 2, 3, 4]
    >>> ("A", "B") + tuple(l[:-1]) + ("C",)
    ('A', 'B', 1, 2, 3, 'C')
    >>> ("A", "B") + tuple(l) + ("C",)
    ('A', 'B', 1, 2, 3, 4, 'C')
    
    0 讨论(0)
  • 2020-12-19 03:55

    As of python 3.5, you can now use your first approach:

    >>> l = [1, 2, 3]
    >>> t = ("AA", "B", *l, "C")
    >>> t
    ('AA', 'B', 1, 2, 3, 'C')
    

    You can use slices just as you'd expect:

    >>> ("AA", "B", *l[:-1], "C")
    ('AA', 'B', 1, 2, 'C')
    

    The related PEP, for reference: PEP448

    0 讨论(0)
  • 2020-12-19 03:56

    You can flatten the list and then convert to tuple.

    >>> import itertools
    >>> l=[1,2,3,4]
    >>> t = ('A', 'B', l, 'C')
    >>> t
    ('A', 'B', [1, 2, 3, 4], 'C')
    >>> tuple(itertools.chain.from_iterable(t))
    ('A', 'B', 1, 2, 3, 4, 'C')
    >>>
    
    0 讨论(0)
提交回复
热议问题