python - 如何创建一个只有一个元素的 "singleton"元组

标签 python tuples

在下面的示例中,我希望所有元素都是元组,为什么元组只包含单个字符串时会转换为字符串?

>>> 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/

相关文章:

python - 如何在 Python 中的两个长列表中减去特定切片的对应元素?

python - 数据帧的减法和赋值返回 NA

python - Openpyxl 优化单元格搜索速度

python - 对元组和嵌套字典求和

python - 按字母顺序列出动物以及哪种动物打败谁

python - 使用嵌套对象在 ModelViewSet 上发布 Django Rest Framework

带有元组表达式的子句中的 JPA 条件

python - 我怎么知道在 Python 中使用什么数据类型?

python - 从字符串到元组的转换 - 双逗号

python - 以编程方式创建一个非文字 python 元组