python集合操作函数_Python 内置函数(集合操作,IO操作)

format()

格式化字符串的函数

>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序

'hello world'

>>> "{0} {1}".format("hello", "world") # 设置指定位置

'hello world'

>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置

'world hello world'

enumerate()

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

>>> seasons = ['a','b','c','d','e']

>>> list(enumerate(seasons))

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

>>>list(enumerate(seasons, start=1)) # 小标从 1 开始

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

#运用for循环

>>>seq = ['one', 'two', 'three']

>>>for i, element in enumerate(seq):

... print(i, seq[i])

...

0 one

1 two

2 three

iter()

iter(object[, sentinel])

用来生成迭代器。object -- 支持迭代的集合对象。sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的 _ _ next _ _()方法时,都会调用 object。

>>>lst = [1, 2, 3]

>>> for i in iter(lst):

... print(i)

...

1

2

3

max() min()

max()返回给定参数的最大值,参数可以为序列。

>>> max(1,2,3)

3

>>> max([1,2,3,99])

99

min()返回给定参数的最小值,参数可以为序列。

>>> min(2,-1,3)

-1

>>> min([0,-1,-2])

-2

dict()

用于创建字典

>>>dict() # 创建空字典

{}

>>> dict(a='a', b='b', t='t') # 传入关键字

{'a': 'a', 'b': 'b', 't': 't'}

>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典

{'three': 3, 'two': 2, 'one': 1}

>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典

{'three': 3, 'two': 2, 'one': 1}

list()

用于将元组或字符串转换为列表。

>>> a = (1,'google','runoob','taobao')

>>> type(a)

>>> list(a)

[1, 'google', 'runoob', 'taobao']

set()

创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。集合中的元素可以动态的增加或删除。

>>> x = set('taobao')

>>> y = set('aobo')

>>> x,y

({'t', 'b', 'o', 'a'}, {'a', 'b', 'o'})

frozenset()

返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

>>>a = frozenset(range(10)) # 生成一个新的不可变集合

>>> a

frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> b = frozenset('runoob')

>>> b

frozenset(['b', 'r', 'u', 'o', 'n']) # 创建不可变集合

str()

将对象转化为适于人阅读的形式。

>>>dict = {'baidu':'baidu.com','google':'google.com'}

>>>str(dict)

"{'baidu':'baidu.com','google':'google.com'}"

sorted()

对所有可迭代的对象进行排序操作

>>>sorted([5, 2, 3, 1, 4])

[1, 2, 3, 4, 5]

>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]

>>> sorted(example_list, reverse=True)

[7, 6, 5, 4, 3, 2, 1, 0]

tuple()

将列表转换为元组。

>>> list1 = ['baidu','google','taobao']

>>> tuple1 = tuple(list1)

>>> tuple1

('baidu', 'google', 'taobao')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值