在下面的示例中,我希望所有元素都是元组,为什么元组只包含单个字符串时会转换为字符串?
>>> a = [('a'), ('b'), ('c', 'd')]
>>> a
['a', 'b', ('c', 'd')]
>>>
>>> for elem in a:
... print type(elem)
...
<type 'str'>
<type 'str'>
<type 'tuple'>
最佳答案
why is a tuple converted to a string when it only contains a single string?
a = [('a'), ('b'), ('c', 'd')]
因为前两个元素不是元组;它们只是字符串。括号不会自动使它们成为元组。您必须在字符串后面添加一个逗号,以向 python 指示它应该是一个元组。
>>> type( ('a') )
<type 'str'>
>>> type( ('a',) )
<type 'tuple'>
要修复示例代码,请在此处添加逗号:
>>> a = [('a',), ('b',), ('c', 'd')]
^ ^
来自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.
如果您确实讨厌尾随逗号语法,解决方法是将 list
传递给 tuple()
函数:
x = tuple(['a'])
关于python - 如何创建一个只有一个元素的 "singleton"元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453740/