Python 如何创建只有一个元素的元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12876177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a tuple with only one element
提问by Russell
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'>
采纳答案by Jonathon Reinhart
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.
因为前两个元素不是元组;它们只是字符串。括号不会自动使它们成为元组。您必须在字符串后添加一个逗号,以向 python 表明它应该是一个元组。
>>> 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:
来自Python 文档:
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.
一个特殊的问题是包含 0 或 1 个项目的元组的构造:语法有一些额外的怪癖来适应这些。空元组由一对空括号构成;包含一项的元组是通过在值后面加上逗号来构造的(将单个值括在括号中是不够的)。丑陋,但有效。
If you truly hate the trailing comma syntax, a workaround is to pass a listto the tuple()function:
如果你真的讨厌尾随逗号语法,一个解决方法是将 a 传递list给tuple()函数:
x = tuple(['a'])
回答by Frédéric Hamidi
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')]
回答by Rohit Jain
('a')is not a tuple, but just a string.
('a')不是元组,而只是一个字符串。
You need to add an extra comma at the end to make pythontake them as tuple: -
您需要在最后添加一个额外的逗号以将python它们视为tuple:-
>>> a = [('a',), ('b',), ('c', 'd')]
>>> a
[('a',), ('b',), ('c', 'd')]
>>>

