问题:如何创建仅包含一个元素的元组
在下面的示例中,我希望所有元素都是元组,为什么当元组仅包含单个字符串时,它会转换为字符串?
>>> a = [('a'), ('b'), ('c', 'd')]
>>> a
['a', 'b', ('c', 'd')]
>>>
>>> for elem in a:
... print type(elem)
...
<type 'str'>
<type 'str'>
<type 'tuple'>
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 = [('a'), ('b'), ('c', 'd')]
>>> a
['a', 'b', ('c', 'd')]
>>>
>>> for elem in a:
... print type(elem)
...
<type 'str'>
<type 'str'>
<type 'tuple'>
回答 0
因为前两个元素不是元组;他们只是字符串。括号不会自动使它们成为元组。您必须在字符串后添加一个逗号,以指示python它应该是一个元组。
>>> type( ('a') )
<type 'str'>
>>> type( ('a',) )
<type 'tuple'>
要修复示例代码,请在此处添加逗号:
>>> a = [('a',), ('b',), ('c', 'd')]
^ ^
从Python文档:
一个特殊的问题是包含0或1项的元组的构造:语法有一些额外的怪癖来容纳这些项。空元组由一对空括号组成;一个带有一个项目的元组是通过在值后面加上逗号来构造的(仅将一个值括在括号中是不够的)。难看,但是有效。
如果您确实讨厌尾随的逗号语法,则一种解决方法是将a传递list
给该tuple()
函数:
x = tuple(['a'])
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'])
回答 1
您的前两个示例不是元组,它们是字符串。单项元组需要逗号结尾,如下所示:
>>> a = [('a',), ('b',), ('c', 'd')]
>>> a
[('a',), ('b',), ('c', 'd')]
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')]
回答 2
('a')
不是一个元组,而是一个字符串。
您需要在末尾添加一个逗号,以使其python
为tuple
:-
>>> a = [('a',), ('b',), ('c', 'd')]
>>> a
[('a',), ('b',), ('c', 'd')]
>>>
('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')]
>>>