python习题

统计列表中元素出现个数

from collections import Counter
import numpy as np

l = ['a', 'b', 'c', 'd', 'a', 'v', 's', 'd', 'c', 'a']

# 方法一:最简单的 Counter 计数法
print(Counter(l).most_common(2))

# 方法二:正常写法先 set 后统计
res = {}
for i in set(l):
    res[i] = l.count(i)
print(res) #集合res

# 方法三: 比较骚的 numpy 计数
arr = np.array(l)
print("#",arr)
key = np.unique(l)  #去重的列表
result = {}
for k in key:
    mask = (arr == k)
    print(mask)
    arr_new = arr[mask]
    print(arr_new)
    v = arr_new.size
    result[k] = v
print(result)

判断一个列表是否为另一个列表的子列表

a = [1,2,3,4,5,6,7]
b = [2,3,0]
#方法一
def in_or_notin():
    for i in b:
        if i not in a:
            return 'no'
            break
    return 'yes'
print(in_or_notin())
#方法二:set.issubse
print(set(b).issubset(set(a)))
原文地址:https://www.cnblogs.com/liuChang888/p/15029196.html