[英]searching a substring in a python list and then removing it from the list
[英]Python: Need help searching through a list for substring
我知道這是一個簡單的問題,但我有一個包含數百個字符串的列表,我需要幫助嘗試 select 其中一些。 例如,列表是:
lines = ["First Sentence dog", "Second Sentence dog", "Third Sentence cat", "Fourth Sentence cat"...]
我需要訪問和操作包含單詞“dog”的索引。 我到目前為止的代碼是:
for line in range(len(lines)):
if "dog" in line:
# Do some something
elif "cat" in line:
# Do some something else
else:
# Do other things
感謝您的任何幫助!
編輯:我得到的錯誤是 TypeError:'int' 類型的參數是不可迭代的
具體來說,我的問題是:如何通過在其中搜索特定的 substring 來檢索整個字符串並對其執行某些操作?
您可以使用enumerate()
:
for i,line in enumerate(lines):
if "dog" in line:
# Do some something
elif "cat" in line:
# Do some something else
else:
# Do other things
enumerate()
將允許您迭代一個可迭代對象以及當前元素的索引。 如果您不需要索引,只需:
for line in lines:
if "dog" in line:
# Do some something
elif "cat" in line:
# Do some something else
else:
# Do other things
您必須使用索引來訪問列表中的字符串。
for line in range(len(lines)):
if "dog" in lines[line]:
# Do some something
elif "cat" in lines[line]:
# Do some something else
else:
# Do other things
你可以試試 map() function。
首先定義 function 您可以在其中做某事:
def change(string):
if string = 'dog':
#do something
else:
#do something
然后嘗試 map() function。 如果您希望 output 作為列表,則:
list(map(change,lines))
lines = [
"First Sentence dog",
"Second Sentence dog",
"Third Sentence cat",
"Fourth Sentence cat",
]
for index, line in enumerate(lines[:]):
if "dog" in line:
lines[index] = "Do Something"
elif "cat" in line:
lines[index] = "Do some something else"
else:
lines[index] = "Do other things"
print(lines)
['Do Something', 'Do Something', 'Do some something else', 'Do some something else']
如果您需要對這些行做些什么,那么您可以考慮先將它們全部收集到一個列表中,然后對它們應用一些 function。 一種方法可能如下:
dog_strings = [x for x in lines if 'dog' in x]
然后您可以將 function 應用於此列表中的所有元素,如下所示:
edited_dog_strings = map(some_function, dog_strings)
所以現在你的代碼由兩行組成(它可能比 for 循環更有效)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.