我刚开始学习Python
我正在阅读tuple
。 Once created, the values of a tuple cannot change.
这是我读的......
如果要一次分配多个变量,可以使用元组:
name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)
我这样做了..
country = 'India'
print(country)
及其修改。
怎么回事?
答案 0 :(得分:6)
使用元组的方式只是将单个值分配给一行中的单个变量。这不会将元组存储在任何位置,因此您将留下4个具有4个不同值的变量。当你改变country的值时,你改变了这个单个变量的值,而不是元组的值,因为字符串变量在python中是“按值调用”。
如果你想存储元组,你可以这样做:
tup = ('Diana',32,'Canada','CompSci')
然后您可以通过索引访问值:
print tup[1] #32
编辑: 我忘了提到的是元组不是可变的,所以你可以访问这些值,但你不能像使用数组那样设置它们。 你仍然可以这样做:
name, age, country, job = tup
但是值将是元组的副本 - 所以改变它们不会改变元组。
答案 1 :(得分:2)
以下代码段代码可能有助于了解原因。在此,name
,age
,country
和career
是单个变量,因此可以进行修改。
t = (name, age, country, career) = ('Diana',32,'Canada','CompSci')
print(t) # ('Diana', 32, 'Canada', 'CompSci')
print(country) # Canada
country = 'India'
print(t) # ('Diana', 32, 'Canada', 'CompSci')
print(country) # India
t[2] = 'India'
# The error occurs as expected
TypeError: 'tuple' object does not support item assignment
答案 2 :(得分:1)
此代码:
name, age, country, career = ('Diana',32,'Canada','CompSci')
print(country)
这样做:
name = 'Diana'
age = 32
country = 'Canada'
career = 'CompSci'
元组不是可变的,但你没有制作元组。要制作元组,请尝试以下方法:
nameAge = ('Diana', 32)
现在你改变了它:
>>> nameAge[1] = 33
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
nameAge[1] = 'a'
TypeError: 'tuple' object does not support item assignment
如你所见,这个元组不会改变。
答案 3 :(得分:0)
您只是更改变量Country而不是元组的值。你可以这样测试:
tup=('Diana',32,'Canada','CompSci')
name,age,country,career = tup
print(country)
country = 'India'
print(tup)
输出应如下:
Canada
('Diana', 32, 'Canada', 'CompSci')
你不能改变元组内部元素的值是不可变的。它是元组的关键特征之一。另一方面,列表是可变的。
答案 4 :(得分:0)
您的要求是使用单行代码将元组 tup 值添加到给定的变量中,例如 name,age,country,career 吗?
问题:
tup = ('Diana',32,'Canada','CompSci')
必需的答案是:
name,age,country,career = tup