日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

关于python直接用列表名复制的一些问题 以及 python 子串查找

發布時間:2024/4/18 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于python直接用列表名复制的一些问题 以及 python 子串查找 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在加載模型中的tensor_name,用到了這部分知識,特此記錄:

舉個例子;

import numpy as npvariables_to_restore = ['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam'] for var in variables_to_restore:print(var)if var.find('Adam')>=0:variables_to_restore.remove(var) print(variables_to_restore)

輸出:?

['wc1', 'wc2', 'wc1/Adam_1', 'wc2/Adam', 'wc1/Adam_1', 'wc2/Adam']

?很明顯我們的代碼,是要找到列表中含子串“Adam” 的字符串并刪除,但是,含“Adam”的明顯沒有被完全刪除,因此筆者開始分析原因,因為variables_to_restore是動態變化的,所以遍歷自然不同,因此筆者猜想,如果遇到刪除的項則刪除,且會跳過下一項,遍歷下下一項。筆者為了驗證自己的想法,特此重新打亂順序做了實驗:

import numpy as npvariables_to_restore = ['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam'] for var in variables_to_restore:print(var)if var.find('Adam_1')>=0:variables_to_restore.remove(var) print(variables_to_restore)

結果:

['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam']['wc1', 'wc2', 'wc1/Adam', 'wc2/Adam_1', 'wc2/Adam', 'wc1/Adam', 'wc2/Adam_1', 'wc2/Adam']

這驗證了筆者的猜想。

那么為了完全刪除應該怎么辦呢?有的同學會想,好,那我重新聲明一個list不就好了,于是開始這樣做:

import numpy as npvariables_to_restore = ['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam'] for var in variables_to_restore:print(var)if var.find('Adam')>=0:variables_to_restore.remove(var) print(variables_to_restore)

?結果:

['wc1', 'wc2', 'wc1/Adam_1', 'wc2/Adam', 'wc1/Adam_1', 'wc2/Adam']

?就驚呆了,明明重新定義了一個list為什么還是不行,其實這就跟python的機制有關系了,直接通過名字來賦值,相當于兩個命名指向同一塊內存區域,操作的時候雖然名字不同,但是是同一數據!!

正確做法:

import numpy as npvariables_to_restore = ['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam'] variables_map = ['wc1','wc2','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam','wc1/Adam','wc1/Adam_1','wc2/Adam_1','wc2/Adam']for var in variables_map:print(var)if var.find('Adam')>=0:variables_to_restore.remove(var) print(variables_to_restore)

結果:

['wc1', 'wc2']

正確的做法是重新將數據賦值給一個新變量,開辟新的內存區域。?

?

PS:python 子串查找

str.find()?#未找到返回-1,找到返回索引>=0list_site.remove(var) #從列表中刪除某個值

?

總結

以上是生活随笔為你收集整理的关于python直接用列表名复制的一些问题 以及 python 子串查找的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。