python - 从字符串对象初始化的列表和元组

标签 python string python-2.7 python-3.x tuples

以下两者有何不同:

>>> s = 'string'
>>> tuple(s)
('s', 't', 'r', 'i', 'n', 'g')
>>> tuple([s])
('string',)
>>> tuple((s))
('s', 't', 'r', 'i', 'n', 'g')
>>> tuple((s,))
('string',)
>>>    

字符串是一个可迭代对象,这就是为什么它在元组中拆分为多个元素?

最佳答案

元组不是由括号决定的,它们是由逗号决定的:

>>> (1)
1
>>> (1,)
(1,)
>>> (1),
(1,)
>>> 1
1
>>> 1,
(1,)

删除中间括号,直到确定表达式:

>>> tuple((((('string')))))
('s', 't', 'r', 'i', 'n', 'g')
>>> tuple((((('string'))),))
('string',)
>>> tuple((((('string'),)),))
(('string',),)

您会看到 Python 如何使用 ast 解析这些表达式

>>> import ast
>>> ast.literal_eval("((((('string')))))")
'string'
>>> ast.literal_eval("((((('string')))),)")
('string',)

并向您展示为什么 tuple(('string'))tuple('string') 相同。额外的括号不会创建元组,只会被解析器丢弃。

关于python - 从字符串对象初始化的列表和元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450396/

相关文章:

python - 艰难地学习 Python ex41 额外学分

python - numpy where 命令在 dtype=object 的数组上

python - 如何从列中获取值并将它们发送到行?

c# - 试图创建随机值字符串

python - 如何从python中的递归函数返回值?

python - 无法安装 M2Crypto 包

python - 计算字典列表中某个值的出现次数

Python 如果存在重复项,如何指定要索引的字符

Java被连续字符分割

string - 使用一些字符串形成给定模式的算法