习题1
将字符串“python”转化为列表(记为lst),然后完成如下操作:
- 将字符串"rust"中的每个字母作为独立元素追加到lst中
- 对lst排序
- 删除lst中重复的元素
>>> s = 'python'
>>> lst = list(s)
>>> lst
['p', 'y', 't', 'h', 'o', 'n']
>>> r = 'rust'
>>> lst.extend(r)
>>> lst
['p', 'y', 't', 'h', 'o', 'n', 'r', 'u', 's', 't']
>>> lst.sort()
>>> lst
['h', 'n', 'o', 'p', 'r', 's', 't', 't', 'u', 'y']
>>> lst.index('t')
6
>>> set(lst)
{'y', 'u', 'r', 'n', 'h', 's', 't', 'p', 'o'}
>>> list(set(lst))
['y', 'u', 'r', 'n', 'h', 's', 't', 'p', 'o']
习题2
编写程序,实现如下功能:
-用户输入国家名称
-打印输出所输入国家名称及其首都
nations = {'China':'Beijing','Japan':'Tokyo','India':'New Delhi','Sweden':'Stockholm','Russian':'Moscow','Germany':'Berlin','UK':'London','French':'Paris','Swiss':'bern','Egypt':'Cairo','Astralia':'Canberra','New Zealand':'Wellington','Canada':'Ottawa','USA':'Washington','Cuba':'Hacana','Brazil':'brasilia'}
name = input('input a name of country:')
capital = nations.get(name)
print('the country:',name)
print('the capital:',capital)
习题3
有如下技术栈名称集合:skills = {‘Python’,‘R’,‘SQL’,‘Git’,‘Tableau’,‘SAS’}
假设自己的技术事: myskills = {‘Python’,‘R’}
-判断自己所掌握的技术是否在上述技术栈范围内
>>> skills = {'Python','R','SQL','Git','Tableau','SAS'}
>>> myskills = {'Python','R'}
>>> r = myskills.intersection(skills)
>>> bool(r)
True
>>> r
{'Python', 'R'}
习题4
找出以下两个字典共有的键:
{‘a’:1,‘b’:2,‘c’:3,‘d’:4}
{‘b’:22,‘d’:44,‘e’:55,‘f’:77}
>>> d1_set = set(d1.keys())
>>> d1_set
{'a', 'b', 'd', 'c'}
>>> d2_set = set(d2.keys())
>>> d2_set
{'f', 'e', 'b', 'd'}
>>> d1_set.intersection(d2_set)
{'b', 'd'}
>>> d1.keys()
dict_keys(['a', 'b', 'c', 'd'])
>>> type(d1.keys())
<class 'dict_keys'>
>>> d1.keys() & d2.keys()
{'b', 'd'}
习题5
字符串: songs = ‘You raise my up so I can stand on mountains You raise my up to walk on stormy seas I am strong when I am on your shoulders You rasie me up to more than I can be’
-制作上述字符串的单词表
-统计每个单词出现的次数
>>> songs = 'You raise my up so I can stand on mountains You raise my up to walk on stormy seas I am strong when I am on your shoulders You rasie me up to more than I can be'
>>> songs_set = set(songs.split())
>>> songs_set
{'than', 'I', 'stormy', 'You', 'me', 'seas', 'my', 'to', 'stand', 'shoulders', 'walk', 'your', 'rasie', 'raise', 'on', 'more', 'can', 'mountains', 'when', 'up', 'am', 'strong', 'be', 'so'}
>>> songs.count('stand')
1