我在 first_list 中有一個 URL 串列。現在我只想獲取那些滿足 argument_lst 條件的 URL。
在argument_lst,我提供了一些具體的域名。如果它們與argument_lst 匹配,我只需要first_list 中的那些URL。
這是我的代碼:
first_list = ['https://www.abc45f.com/r/comments/dummy_url/', 'https://dfc.com/test_test/', 'https://www.kls.com/fsdnfklns_dfdsj','https://example11.com/app/1642038659010248255/']
argument_lst = ['abc45f.com', 'example11.com',5,7,8]
bl_lst = []
for lst in first_list:
all_element = lst
bl_lst.append(all_element)
for l in argument_lst:
if l in bl_lst:
print(l)
我想實作這樣的目標:
https://www.abc45f.com/r/comments/dummy_url/
https://example11.com/app/1642038659010248255/
有人可以幫我嗎?
謝謝
uj5u.com熱心網友回復:
您可以使用例外處理塊來實作它,
first_list = ['https://www.abc45f.com/r/comments/dummy_url/', 'https://dfc.com/test_test/', 'https://www.kls.com/fsdnfklns_dfdsj','https://example11.com/app/1642038659010248255/']
argument_lst = ['abc45f.com', 'example11.com', 5, 7, 8]
output_list = []
for arg in argument_lst:
for el in first_list:
try:
if arg in el:
output_list.append(el)
except TypeError:
continue
print(output_list)
該try-catch
塊將嘗試查找 中的元素argument_list
是否在 的任何元素中first_list
。如果是,則代碼將該成員附加first_list
到output_list
. 如果不是,它只是跳過它。
但是,如果引數不是字串(在您的情況下為整數),則代碼將引發TypeError
例外,因為您將嘗試比較整數和字串。在這種情況下,try-catch
塊將處理例外并繞過它——continue
陳述句將簡單地轉到下一個引數。僅當例外屬于該型別時才會發生這種情況TypeError
,否則仍會導致代碼崩潰。盡可能地縮小代碼正在處理的例外范圍是很重要的,以允許它在實際意外的事情上崩潰。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470710.html
標籤:python-3.x for循环 if 语句 列表理解
上一篇:有沒有更快的方法來根據我必須搜索的其他行中的值來決議和編輯一行中的值?
下一篇:向量串列,其元素之和等于回圈變數