第一题
题目
定义列表:list1 = ['life','is','short'],
list2 = ['you','need','python']
完成以下几个要求:
1)输出python及其下标
2)在list2后追加 '!' , 在 'short' 后添加 ','
3)将两个字符串合并后,排序并输出其长度
4)将 'python' 改为 'python3'
5)移除之前添加的 '!' 和 ','
解答
list1=['life','is','short']
list2=['you','need','python']
python_index=list2.index('python')
print('1. The index is:',python_index,'.','The element is:',list2[python_index])
list2.append('!')
list1.append(',')
print("2.",list1,list2)
list_all=list1.copy()
list_all.extend(list2)
list_all.sort()
print('3. The new list is :',list_all,'.','The length is:',len(list_all))
list2[list2.index('python')]='python3'
print('4.',list2)
list2.remove('!')
list1.remove(',')
print('5.',list1,list2)
运行结果
- The index is: 2 . The element is: python
- ['life', 'is', 'short', ','] ['you', 'need', 'python', '!']
- The new list is : ['!', ',', 'is', 'life', 'need', 'python', 'short', 'you'] . The length is: 8
- ['you', 'need', 'python3', '!']
- ['life', 'is', 'short'] ['you', 'need', 'python3']
第二题
题目
自己定义元组并练习常用方法(输出元组长度、指定位置元素等)
解答
tuple_subway_13=('XiErQi','ShangDi','WuDaokou',)
print('The length of the tuple is:',len(tuple_subway_13))
for i in range(0,len(tuple_subway_13)):
print(i,':',tuple_subway_13[i])
运行结果
The length of the tuple is: 3
0 : XiErQi
1 : ShangDi
2 : WuDaokou
第三题
题目
定义列表:
list1 = ['life','is','short'],
list2 = ['you','need','python']
list3 = [1,2,3,4,5,3,4,2,1,5,7,9]
完成以下操作:
1)构造集合 list_set1
2)将list1和list2合并构造集合 list_set2
3)输出两个集合的长度
4)将两个集合合并后移除 'python'
5)在合并后的新列表中添加 'python3'
解答
list1 = ['life','is','short']
list2 = ['you','need','python']
list3 = [1,2,3,4,5,3,4,2,1,5,7,9]
list_list=list1.copy()
list_set1=set(list_list)
print('1.',list_set1)
list_list.extend(list2)
list_set2=set(list_list)
print('2.',list_set2)
print('3.','The length of set1 is:',len(list_set1),'.','The length of set2 is:',len(list_set2))
list_set_new=list_set1.union(list_set2)
list_set_new.discard('python')
print('4.',list_set_new)
list_set_new.add("python3")
print('5.',list_set_new)
运行结果
- {'short', 'is', 'life'}
- {'you', 'short', 'need', 'is', 'python', 'life'}
- The length of set1 is: 3 . The length of set2 is: 6
- {'you', 'short', 'need', 'is', 'life'}
- {'you', 'short', 'python3', 'need', 'is', 'life'}