Python(序列操作函数)

#all()函数用于判断给定的可迭代参数iterable 中所有元素是否都为true,(除了是0、false、空都为true)
#空元组、空列表都为true.
#序列操作 str、元组、list

print(all([])) #true
print(all(())) #true
print(all[1,2,0])#false

#any() 函数用于判断给定的可迭代参数,是否全部为false.(如果有一个为true,则返回true)

print(any([1,0,False,2])) #true

#sorted() 对所有可迭代的对象进行排序。
#sort是应用在list上的方法,sorted可以对所有可迭代进行排序;
#sort返回的是已经存在的列表,而sorted是返回一个新的列表。

li=[2,24,2,21] 
li.sort()
print('之前的{}'.format(li))
print(sorted(li))
varList=sorted(li) #它不会修改原来的,所以最好要用一个变量来赋值。

print('之后的{}'.format(varList))
varList=sorted(li,reverse=True)
print('降序排序{}'.format(varList))

在这里插入图片描述
#range() 创建一个整数列表,一般用在for循环中。
#range(start,stop[,step])

#zip()就是用来打包的。会吧序列中对应的索引位置的元素存储为一个元组来进行输出。

s1=['a','b','c']
s2=['你','我','他','她']
print(list(zip(s1))) #压缩一个数据
zipList=zip(s1,s2)
print(list(zipList)) #压缩两个数据



例子:图书管理的一个小例子。

def printBook():
    books=[] #存储所有图书信息
    id=input('请输入编号:每项以空格分隔')
    bookName=input('请输入书名')
    bookPos=input('请输入位置')
    idList=id.split(' ')
    nameList=bookName.split(' ')
    posList=bookPos.split(' ')
    
    bookInfo=zip(idList,nameList,posList)
    for bookItem in bookInfo:
        '''图书存储信息 '''
        dictInfo={'编号':bookItem[0],'书名':bookItem[1],'位置':bookItem[2]}        
        books.append(dictInfo)
        pass
    for item in books:
        print(item)
        pass
    
printBook()

在这里插入图片描述

**#enumerate()**函数用于将一个可遍历的数据对象组合成一个索引序列,同时列出数据和1数据下标,一般在for循环中。

listOBJ=['a','b','c']
for item in enumerate(listOBJ):
    print(item)


listOB1=['a','b','c']
for item in enumerate(listOBJ,3):
    print(item)

在这里插入图片描述

它还可以用来遍历字典

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值