美文网首页Python五期爬虫作业
【Python爬虫作业】- 列表、元组、集合

【Python爬虫作业】- 列表、元组、集合

作者: 丽雁解 | 来源:发表于2017-12-20 23:52 被阅读16次

第一题

题目

定义列表: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)

运行结果

  1. The index is: 2 . The element is: python
  2. ['life', 'is', 'short', ','] ['you', 'need', 'python', '!']
  3. The new list is : ['!', ',', 'is', 'life', 'need', 'python', 'short', 'you'] . The length is: 8
  4. ['you', 'need', 'python3', '!']
  5. ['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)

运行结果

  1. {'short', 'is', 'life'}
  2. {'you', 'short', 'need', 'is', 'python', 'life'}
  3. The length of set1 is: 3 . The length of set2 is: 6
  4. {'you', 'short', 'need', 'is', 'life'}
  5. {'you', 'short', 'python3', 'need', 'is', 'life'}

相关文章

网友评论

本文标题:【Python爬虫作业】- 列表、元组、集合

本文链接:https://www.haomeiwen.com/subject/shxowxtx.html