组合数据类型综合练习;
1.组合数据类型练习:
分别定义字符串,列表,元组,字典,集合,并进行遍历。
总结列表,元组,字典,集合的联系与区别。
1 字符串:
s = 'this is string example' for i in s: 输出结果
t h i s i s s t r i n g e x a m p l e
2.列表
ls = s.split() print(ls) print(ls[-1]) print(ls[2:3]) print(ls[1:3]) print(ls[0:3]) 输出结果
['this', 'is', 'string', 'example'] example ['string'] ['is', 'string'] ['this', 'is', 'string']
3.元组
str = ('wjl','www',[1996,7,28]) for i in str: print(i) 输出结果 wjl www [1996, 7, 28]
4.字典
names = ['wjl','wwq','zcj'] scores = ['95','85','70'] d= dict(zip(names,scores)) print(d) 输出结果 {'wjl': '95', 'wwq': '85', 'zcj': '70'}
5.集合
str1 = [2,2,3,4,4,5,6,7] str1 = set(str2) for i in str4: print(i) 输出结果 2 3 4 5 6 7
列表,元组,字典,集合的联系与区别:
列表是用[]括起来,元组是用()括起来的,字典集合都是用{}括起来。
列表是可变序列,可以索引查找元素进行增删,而元组是只读列表,数据不可修改。
字典由一对对键值对组成,键唯一值不唯一,集合是由无序且不重复的数据组成。