python 近期用到的基础知识汇总(六)

1. Python列表索引批量删除.

一开始天真的一个一个用del函数删除如del list[id].然后发现删文件是按间隔来的(一个删除一个不动).后来想想就明白了,删除一个文件的同时list变短了1,索引却继续加1.这样就导致1+1=2.以间隔为2在做删除操作.这是个大坑啊啊!

根据索引批量删除元素的方法如下:

从原列表选取不在索引里的元素重新生成新的list:

files=[filenames[i] for i in range(len(filenames)) if (i not in lid)]

lid删除索引列表,filenames原列表,files重生成的列表.

参考:https://blog.csdn.net/u013893893/article/details/83149364

当然也可以(索引-已删除的个数)来作为del的删除索引,不过比较麻烦.可以作为一种思路具体就不写了.

2.字符串分割函数split。

其实分为str.split和re.split.前者适合于单个分割符的字符串分割,后者多个分割符也能分割。下面贴下我用到的实例:

分割符'[', ';', ']'三个分割符同时分割。

import re
import json
aa='[{"import re": "3573097","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/3573097/"};{"YourID": "4414007","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/4414007/"};]'
bb=re.split('\[|\;|\]',aa)
l = [item for item in filter(lambda x:x != '', bb)]
print(bb)
print(l)
print(l[0])
dict_conditions_insert = json.loads(l[0])
print(dict_conditions_insert)

['', '{"import re": "3573097","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/3573097/"}', '{"YourID": "4414007","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/4414007/"}', '', '']
['{"import re": "3573097","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/3573097/"}', '{"YourID": "4414007","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/4414007/"}']
{"import re": "3573097","PATH": "E:/DcmData/xlc/windows/lung_nodule_raw/3573097/"} <class 'str'>
{'import re': '3573097', 'PATH': 'E:/DcmData/xlc/windows/lung_nodule_raw/3573097/'} <class 'dict'>

参考:https://blog.csdn.net/luke2834/article/details/54588231

3.random.shuffle和random.sample函数:

import random
lst = list(range(10))
slice = random.sample(lst, 10)
print('lstbefore:',lst)
print('slice:',slice)
random.shuffle(lst)
print('lstafter:',lst)

lstbefore: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
slice: [4, 7, 2, 0, 8, 3, 6, 9, 1, 5]
lstafter: [3, 8, 5, 4, 2, 6, 9, 0, 7, 1]

#洗牌
# for i in reversed(range(len(lst))):
#     j = random.randint(0, i)
#     lst[i], lst[j] = lst[j], lst[i]


#记录位置
h = set()
while (len(h) < 10):
    h.add(random.randint(0, 20))

4.ps2019.11.7:Pytorch clamp函数理解:torch.clamp(input, min, max, out=None) → Tensor
将输入input张量每个元素的夹紧到区间 [min,max],并返回结果到一个新张量.操作如下:

      | min, if x_i < min
y_i = | x_i, if min <= x_i <= max
      | max, if x_i > max

如果输入是FloatTensor or DoubleTensor类型,则参数min max 必须为实数,否则须为整数。【译注:似乎并非如此,无关输入类型,min, max取整数、实数皆可。】

参数:

input (Tensor) – 输入张量
min (Number) – 限制范围下限
max (Number) – 限制范围上限
out (Tensor, optional) – 输出张量
参考:https://blog.csdn.net/happyday_d/article/details/84962393,具体例子如下

>>> a = torch.randn(4)
>>> a
-1.4511
-0.6812
 0.3302
-1.7423

[torch.FloatTensor of size 4]

>>> torch.clamp(a, min=-0.5, max=0.5)
-0.5000
-0.5000
 0.3302
-0.5000

[torch.FloatTensor of size 4]
torch.clamp(input, *, min, out=None) → Tensor

猜你喜欢

转载自blog.csdn.net/qq_36401512/article/details/90406248