python 元组的一点问题

元组的一点问题

tuple = ("helloworld", 12, "coding")
print(tuple)
print(tuple[0])
print(type(tuple))

print("### 1 ####")
testTuple = ("helloworld")
print(testTuple)
print(type(testTuple))
print(testTuple[0])

print("### 2 ####")
testTuple = ("helloworld", )
print(testTuple)
print(type(testTuple))
print(testTuple[0])

测试结果:

('helloworld', 12, 'coding')
helloworld
<class 'tuple'>

### 1 ####
helloworld
<class 'str'>
h

### 2 ####
('helloworld',)
<class 'tuple'>
helloworld

从测试程序中,可以看出:

    创建只有一个元素的元组,需要在元素的后面添加一个“,”逗号,使得python能正确识别出元组的元素,否则会被当做字符串处理。

   元组一旦创建,无法修改 删除 添加元素和长度。(打包)

  创建空的元组只需一对空的圆括号:tuple = ( )


 元组的访问

        可通过下标的访问方式,下标索引可以是正数,0,负数(后)

        也可以通过切片的方式访问, 分片索引可以为正数,0,负数(后)


二元元组 

tuple = (("test1", 124), ("test2",), (23, "test3")

和二维数组的访问方式一样。

tuple[0][1] : 124

tuple[0] : ("test1", 124)


遍历的方法和数组基本一样, 循环的方法。


a, b, c, d = tuple #解包

猜你喜欢

转载自blog.csdn.net/baidu_20351223/article/details/80043264
今日推荐