【python】常用操作

python常用操作

—多层序列的遍历

#两层列表嵌套
array=[[1,2],[3,4],[5,6]]
for i in range(len(array)):
    for j in range(len(array[i])):
        print(array[i][j])
输出:
>>123456
        
        
#三层列表嵌套
array=[[[1,2],[3,4]],[[5,6],[7,8]]]
for i in range(len(array)):
    for j in range(len(array[i])):
        for k in range(len(array[i][j])):
            print(array[i][j][k])
输出:
>>12345678

—序列映射map

—过滤器filter

#filter和自定义函数来过滤数值
def f1(c1):
    if c1>10:
        return True
    else:
        return False
destination_digit=list(filter(f1,[1,2,3,50,68]))
print(destination_digit)
输出:
>>[50, 68]

#filter和lambda来过滤指定数据类型
destination_type=list(filter(lambda x:isinstance(x,int),[1,2,3,'1','2','3']))
print(destination_type)
输出:
>>[1, 2, 3]

#filter和lambda来过滤指定字符串
destination_str=list(filter(lambda x:x.isupper(),['CHINA','beijing']))
print(destination_str)
输出:
>>['CHINA']

—键值对调

#字典的键与元组的值对调
d={'sum1':1,'sum2':2,'sum3':3}
y=(4,5,6)
def exchange(c1,c2):
	new_tuple=tuple(c1.keys()) #字典的键 可与元组 集合 列表内的值对调 用tuple set list转换即可
	new_dict=dict(zip(c2,c1.values()))
	return new_dict,new_tuple
new_dict,new_tuple=exchange(d,y)
print(new_dict)
print(new_tuple)
#字典的值与元组的值对调
d={'sum1':1,'sum2':2,'sum3':3}
y=(4,5,6)
def exchange(c1,c2):
	new_tuple=tuple(c1.values()) #字典的值 可与元组 集合 列表 内的值对调 用tuple set list转换即可
	new_dict=dict(zip(c1.keys(),c2))
	return new_dict,new_tuple
newdict,newtuple=exchange(d,y)
print(newdict)
print(newtuple)

—遍历目录的函数

import os
def travel_dir(dress):
	dir_contents=os.listdir(dress)                         #获取目录下的内容
	dir_content="\n".join(dir_contents)                    #将列表形式内容转化为字符串
	print("目录:{} \n内容:\n{}\n".format(dress,dir_content))
	for i in dir_contents:                                 #遍历列表的内容
		try:
				new_dir=os.path.join(dress,i)              #拼接成绝对路径
				if os.path.isdir(new_dir):                 #选择是目录的绝对路径
					travel_dir(new_dir)                    #调用函数自身继续操作
		except PermissionError:continue                    #排除有权限异常的目录
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值