python笔记-集合

Created at 2020-09-10 Updated at 2021-12-12 Category python Tag python

list

使用append()pop()可以在list 的末尾插入或者删除元素。

list 支持切片操作,切片是从原list拷贝出指定的一段。

使用start:end[:step]来获取切片,是一个左闭右开的区间。留空则表示全部获取,我们也可以额外设置一个参数来表示步长,步长设置成 -1 表示反向遍历

li2 = li[:] # 可以获得li的拷贝

两个list 相加等于使用extend()方法。

li + li2 
li.extend(li2)

list去重方法

run_function = lambda x, y: x if y in x else x + [y]  # list去重
self.oEntity[key]["@value"] = reduce(run_function, [[], ] + self.oEntity[key]["@value"])

list 判断相等

元素顺序不同会判定为不想等,所以可以先排序。

list1 = ["one","two","three"]
list2 = ["one","three","two"]
# 改变list本身
list1.sort()
list2.sort() 
# 不改变list本身
list1 = sorted(list1)
list2 = sorted(list2) 

循环中删除

  • 倒序循环遍历

    for item in num_list_3[::-1]:
  • 遍历copy的list,操作原始list

    for item in num_list_4[:]:

tuple

tuple 表示元组,tuple不可变对象,如果修改tuple对象,会引发TypeError异常。

tup = (1,2,3)
tup = (1,) # 定义单个tuple,末尾必须加逗号,否则()会被认为是其他含义

我们可以用多个变量来解压一个tuple

# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
# You can also do extended unpacking
a, *b, c = (1, 2, 3, 4)  # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6  # tuple 4, 5, 6 is unpacked into variables d, e and f
# respectively such that d = 4, e = 5 and f = 6
# Now look how easy it is to swap two values
e, d = d, e  # d is now 5 and e is now 4

上面的*b表示这是一个 list

tuple本身是不可变的,但是tuple里面的元素是可变的,比如里面有一个list,那么这个list就可以改变。

dict

dict存储键值对,用{}表示一个dict,用:分隔keyvalue

dictkey必须为不可变对象,所以list、set 和 dict 不可以作为另一个 dict 的 key,否则会抛出异常。

[]get()都可以获得value,但是dict可以为不存在的key返回一个默认值,默认为None,用[]会引发KeyError异常。

# Looking up a non-existing key is a KeyError
filled_dict["four"]  # KeyError

# Use "get()" method to avoid the KeyError
filled_dict.get("one")      # => 1
filled_dict.get("four")     # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4)   # => 1
filled_dict.get("four", 4)  # => 4

keys()方法可以返回所有的keyvalues()方法可以返回所有的value

使用in可以判断一个key是否在dict中。

setdefault()方法可以为不存在的 key插入一个value,如果key已经存在,则不会覆盖它。

合并

key相同,y覆盖x

x = {'a': 2, 'b': 2}
y = {'b': 5, 'c': 3}

# python3
z = {**x, **y}
# python2
z = x.copy()
z.update(y) 

# {'a': 2, 'b': 5, 'c': 3}

相加

利用collections.Counter

from collections import Counter
dict(Counter(x) + Counter(y))
# {'a': 2, 'b': 7, 'c': 3}
Site by Cellophane using Hexo & Random

Hide