How to create a tuple with only one element

前端 未结 3 1327
执笔经年
执笔经年 2020-11-22 00:43

In the below example I would expect all the elements to be tuples, why is a tuple converted to a string when it only contains a single string?

>>> a         


        
相关标签:
3条回答
  • 2020-11-22 01:23

    Because those first two elements aren't tuples; they're just strings. The parenthesis don't automatically make them tuples. You have to add a comma after the string to indicate to python that it should be a tuple.

    >>> type( ('a') )
    <type 'str'>
    
    >>> type( ('a',) )
    <type 'tuple'>
    

    To fix your example code, add commas here:

    >>> a = [('a',), ('b',), ('c', 'd')]
    
                 ^       ^
    

    From the Python Docs:

    A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

    If you truly hate the trailing comma syntax, a workaround is to pass a list to the tuple() function:

    x = tuple(['a'])
    
    0 讨论(0)
  • 2020-11-22 01:23

    Your first two examples are not tuples, they are strings. Single-item tuples require a trailing comma, as in:

    >>> a = [('a',), ('b',), ('c', 'd')]
    >>> a
    [('a',), ('b',), ('c', 'd')]
    
    0 讨论(0)
  • 2020-11-22 01:36

    ('a') is not a tuple, but just a string.

    You need to add an extra comma at the end to make python take them as tuple: -

    >>> a = [('a',), ('b',), ('c', 'd')]
    >>> a
    [('a',), ('b',), ('c', 'd')]
    >>> 
    
    0 讨论(0)
提交回复
热议问题