python下list Counter以及列表生成式使用

248 阅读1分钟

Counter使用

统计list中元素出现的次数

# 方法一
List = [1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
List_set = set(List)
for item in List_set:
    print("the %d has found %d" %(item,List.count(item)))

"""
the 1 has found 2
the 2 has found 5
the 3 has found 3
the 4 has found 4
the 5 has found 2
the 6 has found 2
"""

#方法二
from collections import Counter
print(Counter(List)) #Counter({2: 5, 4: 4, 3: 3, 1: 2, 5: 2, 6: 2}) # Counter 属于dict

列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

ls = (x * x for x in range(1, 11))
print(ls) #<generator object <genexpr> at 0x10d33df00>
print(list(ls)) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 拓展
#类似三目表达式
q = [x if x%3==0 else -x for x in range(1,20)]
print(q) # [-1, -2, 3, -4, -5, 6, -7, -8, 9, -10, -11, 12, -13, -14, 15, -16, -17, 18, -19]
p = [x for x in range(1,9) if x%3 == 0]
print(p) # [3,6]

增删改查

list1 = ['dawa', 'erwa', 'sanwa', 'siwa', 'wuwa']

# 增加 
list1.append('liuwa')  #尾部追加
print(list1) #['dawa', 'erwa', 'sanwa', 'siwa', 'wuwa', 'liuwa']
list1.insert(1, 'nazha') #位置追加
print(list1) #['dawa', 'nazha', 'erwa', 'sanwa', 'siwa', 'wuwa', 'liuwa']

# 删除 
list1.pop()   #liuwa #尾部删除
print(list1)  #['dawa', 'nazha', 'erwa', 'sanwa', 'siwa', 'wuwa']
list1.pop(1)  #nawa #返回删除位置的元素
print(list1)  #['dawa', 'erwa', 'sanwa', 'siwa', 'wuwa']

# 改
list1[0] = 'wa'
print(list1)   #['wa', 'erwa', 'sanwa', 'siwa', 'wuwa']

# 查
print(list1[0]) #wa
# 切片
print(list1[0:3]) # ['wa', 'erwa', 'sanwa']
print(list1[-5:]) #['wa', 'erwa', 'sanwa', 'siwa', 'wuwa']
print(list1[-1]) #wuwa

#遍历
for item in list1:
    print(item)

# 输出如下
"""
wa
erwa
sanwa
siwa
wuwa
"""

# 遍历
for k,value in enumerate(list1):
    print(k,value)
# 输出
"""
(0, 'dawa')
(1, 'erwa')
(2, 'sanwa')
(3, 'siwa')
(4, 'wuwa')
"""

参考知识

列表生成式