1.?Python列表索引批量刪除.
python語言程序設計、一開始天真的一個一個用del函數刪除如del list[id].然后發現刪文件是按間隔來的(一個刪除一個不動).后來想想就明白了,刪除一個文件的同時list變短了1,索引卻繼續加1.這樣就導致1+1=2.以間隔為2在做刪除操作.這是個大坑啊啊!
根據索引批量刪除元素的方法如下:
python 列表。從原列表選取不在索引里的元素重新生成新的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.68120.3302
-1.7423[torch.FloatTensor of size 4]>>> torch.clamp(a, min=-0.5, max=0.5)
-0.5000
-0.50000.3302
-0.5000[torch.FloatTensor of size 4]
torch.clamp(input, *, min, out=None) → Tensor
?
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态