tuple - 元组 - 只读
my_list = [1,2,3,4,5] # 列表
my_tuple = (1,2,3,4,5) # 元组
my_set = {1,1,2,2,3,3} # 集合
print(my_set) # 集合会去除重复元素
set1 = {1,2,3}
set1.add(4)
set1.add(5)
print(set1)
set2 = {1,3,5,7,9}
set3 = set1.intersection(set2)
print(set3)
set3 = set1.union(set2)
print(set3)
set3 = set1.difference(set2)
print(set3)
set3 = set2.difference(set1)
print(set3)
set3 = set1.symmetric_difference(set2)
print(set3)
for val in set2:
print(val,end=' ')
print(set2.pop())
if 3 in set2:
set2.remove(3)
print(set2)
print(set2.issubset(set1))
print(set2.issuperset(set1))
例1:列表与元组的应用
def main():
set4 = {'hello','apple','good','banana','zoo','hello'}
print(len(set4))
x = sorted(set4)
print(x)
print(type(x))
list1 = list(set4)
print(list1)
list2 = [1,2,3,1,2,4]
set5 = set(list2)
print(set5)
tuple1 = (1,1,2,3,4,4)
list3 = list(tuple1)
print(list3)
if __name__ == '__main__':
main()
小结:列表与元组的转化,一些相关运用。
例2:姓名与成绩
def main():
names = ['关羽','张飞','刘备','吕布','貂蝉']
subjects = ['语文','数学','Python']
table = []
for row,name in enumerate(names):
print('请输入%s的成绩:'%name)
scores =[]
table.append(scores)
for col,subject in enumerate(subjects):
score = int(input('%s:'%(subject)))
scores.append(score)
print(table)
if __name__ == '__main__':
main()
def main():
names = ['关羽','张飞','刘备','吕布','貂蝉']
subjects = ['语文','数学','Python']
scores = [[0 for _ in range(3)] for _ in range(5) ]
print(scores)
for row,name in enumerate(names):
print('请输入%s的成绩:'%name)
for col,subject in enumerate(subjects):
scores[row][col] = int(input('%s:'%(subject)))
print(scores)
if __name__ == '__main__':
main()
例3:# 函数,年,月,日,返回 年月日是这一年的第几天。
def is_leap_year(year):
return year % 4 ==0 and year % 100 != 0 or year % 400 == 0
def which_day(year,month,date):
day_of_month = [31,28,31,30,31,30,31,31,30,31,30,31]
total = 0
for n in range(month-1):
total += day_of_month[n]
if month > 2 and is_leap_year(year):
total += 1
return total + date
if __name__ == '__main__':
main()
字典
def main():
dict1 = {'name':'xl','age':'20','gender':'sex','hehe':'yoyo'}
print(dict1['name'])
dict1['name'] = 'fuck'
print(dict1)
dict1.update(h='180', f=['c','h','p','d'])
print(dict1)
print(dict1.pop('age'))
print(dict1.popitem())
dict1['name'] = None
del dict1['gender']
dict1.setdefault('hehe','haha')
print(dict1['hehe'])
for x in dict1:
print(x,'----->',dict1[x])
dict1.pop('hehe')
print(dict1['hehe'])
if __name__ == '__main__':
main()
小结:字典的基本运用。