python 基础小tips

map(fun, [])

(python 3.x 中map函数返回的是iterators,无法像python2.x 直接返回一个list,故需要再加上一个list()将iterators转化为一个list)。

1.    lambda: x f(x), [1,2,3...]

有人说类似于一种匿名函数,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用

map, lambda 合用:

list(map(lambda x: x*x, [0,1,2]))

 

zip 加速读取数据

注意*的使用:返回的是迭代器

    strs = ['1434','124','123']
        for one in zip(*strs): 
            tmp = set(one) #第i次进入循环的结果:(1,1,1) (4,2,2)... ->{1}, {2,4}...
            if len(tmp) != 1:
                return re
                break

            re += tmp.pop()

 

pass 语句的用途:

https://blog.csdn.net/violet_echo_0908/article/details/52052054

1. if ... else ...

if a==b and c==d and e==f:
pass # 并不想做任何事
else:
task # 知识想在上述条件的对立面执行,但对立面不容易写条件

 

2. 构建框架的时候

 

def iplaypython():    
    pass

3. while

while True:
    pass

4. 得到排序数组的下标

      原理:让下标一起进行排序

  a = [3,4,1,7,2]

  b = zip(a, range(a))
  b.sort(key = lambda x : x[0])
  c = [x[1] for x in b]

5.遍历某种后缀结尾的文件:

import os, shutil
def scan_all_files_path(root, sort=True, key=None, show=False):
    '''
    scan_all_files_path  in root path
    '''
    print('scan root: ', root)
    file_paths = []
    file_names = []
    for root,dirs,files in os.walk(root):
        if show:
            print("scaning :", root)
        if sort:
            files = sorted(files)
        for file in files:
            full_path = os.path.join(root, file)
            if key != None:
                if os.path.isfile(full_path) and full_path[-len(key):] == key:
                    file_names.append(file)
                    file_paths.append(full_path)
            else:
                if os.path.isfile(full_path):
                    file_names.append(file)
                    file_paths.append(full_path)
    
    print('total file_names: {} and after set num: {}'.format(len(file_names), len(list(set(file_names)))))
    print('total file_paths: {} and after set num: {}'.format(len(file_paths), len(list(set(file_paths)))))
    
    return file_paths, file_names

 

实际使用的主函数用例:

   
source1 = '原始数据主目录'
source2 = '保存的路径'
file_full_paths, filenames = scan_all_files_path(source1, key='jpg', show=True)
for idx, file_full_path in enumerate(file_full_paths):
    source2path = os.path.join(source2, filenames[idx])
    shutil.copy(file_full_path, source2path)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值