Tuple (tuple) is similar to the list, press element is arranged in a specific sequence composition, but it is immutable sequence.
Tuple all the elements on the "()", two adjacent elements use a comma "," separator
Tuples are immutable sequence, a variable sequence listing, tuple elements can not be individually modified, the list can be modified
Python lists and tuples in a sequence are also suitable for a general purpose operating element group, including the use for loop
1.1 yuan to create and delete groups
Using the assignment operator '=', creating a tuple
# 创建空元组
Type =()print(type(Type))# 输出<class 'tuple'># 创建数值元组
Team ="1",1print(Team)# 输出('1', 1) 元组小括号也不是必须的,只要用一组逗号分隔,Python就认为是元组print(type(Team))# 输出<class 'tuple'>#注意使用","
Ver =("四月是你的谎言",)
Ver1 =("四月是你的谎言")print(type(Ver))# 输出<class 'tuple'>print(type(Ver1))# 输出<class 'str'>
The del statement to remove the tuple
# del tuplename 删除元组,在实际开发不常用,Python自带垃圾回收机制,自动销毁不用元组,# 所以即使不手动删除,Python也会自动将其收回
Team =("1",1)del Team
print(Team)# 报错NameError: name 'Team' is not defined说明已删除
1.2 Access tuple element
Function index outputs of all tuples (subscript) value tuple access, or to print ()
# 使用下标获取元组的值
Team =(1,"四月")print(Team[0])# 输出1print(Team[3])# 下标越界报错IndexError: tuple index out of range
1.3 modify tuples
Tuples are immutable sequence, the individual elements can not be modified, but not the tuple can not be completely modified, may be reassigned tuple
Tuples can be connected combination, must all be connected to the content of tuples, tuples and strings, lists can not be connected, or will be error
# 对元组重新赋值
Team =(1,2)
Team =(3,4)print(Team)# 输出(3, 4)# 对元组进行连接组合
player =("四月","是")
player1 =("你的","谎言")print(player+player1)# ('四月', '是', '你的', '谎言')
1.4 two-dimensional tuples
t1 =((1,2,3),(4,5,6))# 遍历for elem in t1:print(elem)for value in elem:print(value, end =' ')print('')'''
环获取到(1, 2, 3) 通过下一个for循环获取单个元素的值
其次获取(4, 5, 6),在词经过for循环获取剩余元素的值
输出:
(1, 2, 3)
1
2
3
(4, 5, 6)
4
5
6
'''
Tuples and lists belong sequence, storing a set of elements in a certain order, the type is not limited, as long as the type of support Python
Variable sequence is a list, modify, or delete elements may at any time; immutable sequence of tuples, tuples can not be modified unless it is replaced by
Tuple processing speed faster than the access list, if the value of access to the list, not the proposed changes tuple
The list can not serve as a dictionary key, tuples can
2. Job
2.1 Calculation prime numbers less than 1000
# 用n遍历 2值999之间的数for n inrange(2,1000):# 用i遍历nfor i in(2,n):# 如果n能整除说明不是素数if n % i ==0:break# 不是素数就输出else:print(n,end=" ")
2.2 star print triangular, simplified version
i =1
num =eval(input("请输入一个整数:"))while i < num:print(" "*(num - i),"*"*(2* i -1))
i +=1'''
输入4,打印:
*
***
*****
'''