最近有个小需求,需要对指定层数的目录进行遍历查找
import os
def SearchAbsPath(root_path):
root_depth = len(root_path.split(os.path.sep))
c, d = [], []
for root, dirs, files in os.walk(root_path, topdown=True):
for name in dirs:
dir_path = os.path.join(root, name)
dir_depth = len(dir_path.split(os.path.sep))
if dir_depth == root_depth + 1
c.append(dir_path)
elif dir_depth == root_depth + 2:
d.append(dir_path)
else: break
return c, d
打印进度条
# 方式一
import time
for i in range(0, 101, 2):
time.sleep(0.1)
char_num = i // 2
per_str = '\r%s%% : %s\n' % (i, '*', * char_num) if i == 100 else '\r%s%% : %s' % (i, '*', * char_num)
print(per_str, end='', flush=True)
# 方式二
from tqdm import tqdm
import time
for i in tqdm(range(10)):
time.sleep(1)
列表嵌套展开
lst =[1,[2],[[3]],[[4,[5],6]],7,8,[9]]
def flat(nums):
res = []
for i in nums:
if isinstance(i, list):
res.extend(flat(i))
else:
res.append(i)
return res
new_lst = flat(lst)
print(new_lst)`
字典互换键值对
三种方式交换键值对(前提:值唯一):
1.
mydict={"a":1,"b":2,"c":3}
mydict_new={}
for key,val in mydict.items():
mydict_new[val]=key
2.
mydict={"a":1,"b":2,"c":3}
mydict_new=dict([val,key] for key,val in mydict.items())
3.利用zip运算符:
mydict={"a":1,"b":2,"c":3}
mydict_new=dict(zip(mydict.values(),mydict.keys()))
twosum
class Solution(object):
def twoSum(self, nums, target):
result = []
for i in range(0,len(nums)):
oneNum = nums[i]
twoNum = target - oneNum
if twoNum in nums:
j = nums.index(twoNum)
if i != j:
result.append(i)
result.append(j)
return result`
网友评论