python爬虫面试基础

warning: 这篇文章距离上次修改已过414天,其中的内容可能已经有所变动。
'''
统计如下list单词及其出现的次数。
'''
a=['apple', 'banana', 'apple', 'tomato', 'orange', 'apple', 'banana', 'watermeton']

dic={}
for key in a:
    dic[key]=dic.get(key,0) +1
print(dic)

#等同于

for key in a:
    if key in dic.keys():
        dic[key]=dic[key]+1
    else:
        dic[key]=1
print(dic)

'''
给列表中的字典排序(例如有如下list对象,将alist中的元素按照age从小到大排序)
'''
alist=[{"name":"a", "age":20}, {"name":"b", "age":30}, {"name":"c", "age":25}]
# 法一
for i in range(1,len(alist)):
    for j in range(0,len(alist)-i):
        if alist[j].get('age')>alist[j+1].get('age'):
            alist[j],alist[j+1]=alist[j+1],alist[j]
print(alist)
#法二
alist.sort(key=lambda x: x['age'])
print(alist)
最后修改于:2023年04月02日 16:03

添加新评论