如何创建只有一个元素的元组 [英] How to create a tuple with only one element

查看:61
本文介绍了如何创建只有一个元素的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>a = [('a'), ('b'), ('c', 'd')]>>>一种['A B C D')]>>>>>>对于 a 中的元素:... 打印类型(元素)...<输入'str'><输入'str'><输入元组">

解决方案

当元组只包含一个字符串时,为什么要转换为字符串?

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

因为前两个元素不是元组;它们只是字符串.括号不会自动使它们成为元组.你必须在字符串后面添加一个逗号来向python表明它应该是一个元组.

<预><代码>>>>类型(('a'))<输入'str'>>>>类型(('a',))<输入元组">

要修复您的示例代码,请在此处添加逗号:

<预><代码>>>>a = [('a',), ('b',), ('c', 'd')]^ ^

来自 Python 文档:

<块引用>

一个特殊的问题是包含 0 或 1 个项目的元组的构造:语法有一些额外的怪癖来适应这些.空元组由一对空括号构成;包含一项的元组是通过在值后面加上逗号来构造的(将单个值括在括号中是不够的).丑陋,但有效.

如果你真的讨厌尾随逗号语法,一个解决方法是将 list 传递给 tuple() 函数:

x = tuple(['a'])

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

解决方案

why is a tuple converted to a string when it only contains a single string?

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

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'])

这篇关于如何创建只有一个元素的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆