[英]Python - Return substring of string that can change
[英]Python: Return string if substring in string
我有兩個列表,一個具有一堆路徑,例如:“ C:\\ vol001 \\ ABC123.xls”,另一個具有一堆名稱,例如:“ ABC123”。 如果名稱在路徑中,我正在尋找路徑。 因此,對於上面的示例,該程序將吐出“ C:\\ vol001 \\ ABC123.xls”。
到目前為止,我一直在嘗試使用in運算符,但是我不確定如何返回路徑。
for name in list1:
if name in list2:
return path in list2
您最初的解決方案不正確。 實際上,您是在問“列表中是否有'name' 等於項目之一”。 但是,如果您想測試是否包含 ,即“列表中是否包含'名稱' ,請使用下面的代碼:
for name in l2:
return [x for x in l1 if name in x]
它是匹配路徑的返回列表。 實際上, 對於以更Python方式重寫的循環來說,它只有2個(我記得它被稱為“列表理解”,如果我錯了,更熟悉術語的人會修復我)。
我認為這是您想要的:
for path in list1:
for name in list2:
if name in path:
return path
else:
return None # not found
這對您有用嗎?
new_paths = [] # create list for the paths to be kept
for path in paths: # cycle through paths
for name in names: # cycle through names
if name in path: # check if path contains the name
new_paths.append(path) # path is good, so add to the list
考慮到您的評論,名稱出現在路徑中的位置無關緊要(即“ C:\\ ABC123 \\ test.png”和“ C:\\ vol01 \\ ABC123.xml”都與查詢“ ABC123”匹配) ,我們不考慮文件系統路徑的結構,但可以進行純字符串匹配。
是路徑,是所有paths
的列表,是names
,是所有名稱的列表,然后是name
是您要查找的名稱,然后
(path for path in paths if name in path)
是生成與名稱匹配的所有路徑的生成器。
dict ( ( (name, [path for path in paths if name in path] ) for name in names) )
創建一個字典,該字典的鍵是名稱,其值是包含相應名稱的所有路徑。 您可以這樣使用它:
paths = [....]
names = [....]
d = dict ( ( (name, [path for path in paths if name in path] ) for name in names) )
print ('The name "ABC" is contained in: {}'.format (d ['ABC'] ) )
print ('The name "XYZ" is contained in: {}'.format (d ['XYZ'] ) )
print ('The name "pron" is contained in: {} different paths'.format (len (d ['pron'] ) if 'pron' in d else 0) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.