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')