企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC=1,5] >[success] # `*` 在 python 用法技巧 *加变量 用来接收一组数据变成列表,使用的时候 直接使用变脸等于列表 >[danger] ##### 案例一 打印结果`['2', '3', '5']` ~~~ def drop_first_last(grades): first,*middle,last = grades return middle grades =["1","2","3","5","6"] test = drop_first_last(grades) print(test) ~~~ >[danger] ##### 案例二 打印结果`['AMY', 'SUM']` ~~~ recored = ('Dave','AMY','SUM',"DAMING") first,*middle,last = recored print(middle) ~~~ >[danger] ##### 案例三-sum 可以直接求列表的和 打印结果`5` ~~~ recored = (1,2,3,4) first,*middle,last = recored print(sum(middle)) ~~~ >[danger] ##### 案例四-for循环配合* 打印结果`foo [1, 2] bar ['hello'] foo [1, 2]` ~~~ records = [ ('foo',1,2), ('bar','hello'), ('foo',1,2), ] for tag,*args in records: print(tag,args) ~~~ >[danger] ##### 案例五-* 配合split 打印结果`['*', '-2', '-2']` ~~~ line = "nobody:*:-2:-2:Unprivilleged" first,*middle,last = line.split(":") print(middle) ~~~ >[danger] ##### 案例六-*_舍弃一组值 打印结果`d` ~~~ line = "nobody:*:-2:-2:Unprivilleged" first,*_,last = line print(last) ~~~ >[danger] ##### 案例六- 对列表的拆分 会拆分成,单个值和一组列表 打印结果`1 [2, 3, 4, 5, 6, 7]` ~~~ line = [1,2,3,4,5,6,7] first,*last = line print(first,last) ~~~ >[danger] ##### 案例七,利用*递归 打印结果`28` ~~~ line = [1,2,3,4,5,6,7] def sum(line): header,*middle = line return header+sum(middle) if middle else header print(sum(line)) ~~~