4
>>> list=['Hello']
>>> tuple(list)
('Hello',)

为什么是上述语句的结果('Hello',)而不是('Hello')?。我原以为会是后者。

4

1 回答 1

12

你做对了。如果你这样做,在 python 中:

a = ("hello")

a将是一个字符串,因为此上下文中的括号用于将事物组合在一起。实际上是逗号构成了一个元组,而不是括号(括号只是为了避免在某些情况下(如函数调用)产生歧义)......

a = "Hello","goodbye"  #Look Ma!  No Parenthesis!
print (type(a)) #<type 'tuple'>
a = ("Hello")
print (type(a)) #<type 'str'>
a = ("Hello",)
print (type(a)) #<type 'tuple'>
a = "Hello",
print (type(a)) #<type 'tuple'>

最后(也是最直接的问题):

>>> a = ['Hello']
>>> b = tuple(a)
>>> print (type(b))  #<type 'tuple'> -- It thinks it is a tuple
>>> print (b[0])  #'Hello' -- It acts like a tuple too -- Must be :)
于 2013-01-30T15:08:18.190 回答