python入门笔记——内置函数②(序列操作函数和集合操作函数)
# 序列操作函数
# all,any,sorted,reverse,range,zip,enumerate
print(all([1,2,3]))
print(all([1,2,3,0]))
# all:用于判断给定的可迭代参数iterable中的所有元素是否都为True
# 如果是返回True,否则返回False
# 元素除了是0、空、None、False外都算True
print(any([0,'',1]))
print(any([0,False,'']))
# any:用于判断给定的可迭代参数iterable是否全部为False,则返回False,如果有一个为True,则返回True
# 元素除了是0、空、False外都算True
print(sorted([6,2,4,9,1,3,8],reverse=True))
print(sorted([6,2,4,9,1,3,8],reverse=False))
# sorted:对所有可迭代的对象进行排序操作,reverse排序规则,reverse=True降序,reverse=False升序(默认)
# sorted语法是:sorted(iterable, key=None, reverse=False)
# 故还有更复杂的使用:
student = [('zs',10),('ls',15),('wemz',13)]
listA = [100,200,150]
print(sorted(student,key=lambda x:x[1]))# 默认升序可不写
print(sorted(student,key=lambda x:x[1],reverse=True))
# 注:python3中没有内置的cmp函数!!!
# 也可以使用sort方法,但使用方式不同:
listA.sort()# 默认升序,listA.sort(reverse = True)即为降序
print(listA)
listB = ['zs','ls','wwmz']
listB.reverse()
print(listB)# reverse()函数用于反向列表中元素
# range:前面已用过range函数,这里写range在另一个地方的用法
listC = list(range(0,30,5))
print(listC)
# 注意左闭右开,这里为例,0为起始,30为结束(不能取),5为步长
zip1 = zip(['a','b','c','d'],[1,2,3])
print(list(zip1))
# zip:可以说类似于笛卡儿积,记得要转换成列表才能查看
# 前面创建了listB = ['zs','ls','wwmz']
print(list(enumerate(listB)))
# numerate:用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
# 同时列出数据和数据下标,一般用在for循环当中,可优化某些for循环使用
# 普通for循环:
# i = 0
# seq = ['one', 'two', 'three']
# for element in seq:
# print(i, seq[i])
# i += 1
# 优化后:
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
# 集合操作函数
# add,clear,difference,intersection,union,pop,discard,update
fruit = {'apple','banana','pear'}
fruit1 = {'apple','pineapple'}
fruit.add('orange')
print(fruit)
# add:往集合里添加元素,已存在的元素则不执行添加
test_clear = {'a','b','c'}
test_clear.clear()
print(test_clear)
# clear:移除集合中所有元素,会输出set()
fruit_difference = fruit.difference(fruit1)
print(fruit_difference)
# difference:用于返回集合的差集,即返回的集合元素包含在x集合中,但不包含在y集合中
fruit_intersection = fruit.intersection(fruit1)
print(fruit_intersection)
# intersection:用于返回两个或更多集合中都包含的元素,即交集
fruit_union = fruit.union(fruit1)
print(fruit_union)
# union:返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次
test_pop = {1,3,5,7}
test_pop.pop()
print(test_pop)
# pop:用于随机移除一个元素,注意,是随机
test_discard = {2,4,6,8}
test_discard.discard(6)
print(test_discard)
# discard:用于移除指定的集合元素
# discard不同于remove,因为remove在移除一个不存在的元素时会发生错误,而discard不会
test_update1 = {1,2,3,4}
test_update2 = {3,4,5,6}
test_update1.update(test_update2)
print(test_update1)
# update:用于修改当前集合,可以添加新的元素或集合到当前集合中
# 如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略
输出结果:
True
False
True
False
[9, 8, 6, 4, 3, 2, 1]
[1, 2, 3, 4, 6, 8, 9]
[('zs', 10), ('wemz', 13), ('ls', 15)]
[('ls', 15), ('wemz', 13), ('zs', 10)]
[100, 150, 200]
['wwmz', 'ls', 'zs']
[0, 5, 10, 15, 20, 25]
[('a', 1), ('b', 2), ('c', 3)]
[(0, 'wwmz'), (1, 'ls'), (2, 'zs')]
0 one
1 two
2 three
{'orange', 'pear', 'apple', 'banana'}
set()
{'orange', 'pear', 'banana'}
{'apple'}
{'orange', 'pineapple', 'apple', 'banana', 'pear'}
{3, 5, 7}
{8, 2, 4}
{1, 2, 3, 4, 5, 6}