Pythonの容器——tuple

tuple
  1. 特点

    定义范围使用()进行包围,元素之间也是通过,进行分隔。

    元素中可以存在List的元素

    t = (1024,3.14,[2,3,4],'python')
    print(t)
    # (1024, 3.14, [2, 3, 4], 'python')
    
    print(type(t))
    # <class 'tuple'>
    
  2. 和List相同,Tuple可以使用下标,但不同于List的下标操作,Tuple中的元素不可以修改。

    print(t[2])
    # [2, 3, 4]
    
    t[0] = 1
    '''Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        t[0] = 1
    TypeError: 'tuple' object does not support item assignment'''
    
  3. Tuple相较于List,空间占用小一些

    image.png

  4. 创建解析式

    nums = (x**2 for x in range(5))
    for i in nums:
    	print(i,end=" ")
    
    #  0 1 4 9 16 
    

猜你喜欢

转载自www.cnblogs.com/zhaojia1024/p/12811287.html