[英]For loop: retaining exact strings (with spaces and quotations) to identify word occurence (python)
在這里遇到編碼挑戰,我正在編寫一個 function ,它需要兩個 arguments (字符串。查詢)並打印每個查詢字符串在輸入字符串中出現的次數。 我想我已經很接近解決這個問題了,但是我的 function 目前對查詢字符串之前/之后帶有空格的查詢字符串不敏感。
版本 1(對包含空格的查詢字符串不敏感):
strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']
def matchingStrings(strings, queries):
for i in range(len(queries)):]
n_matches = strings.count(queries[i])
print(n_matches)
matchingStrings(strings,queries)
當前 Output:
1
0
0
版本 2(嘗試保留引號):
def matchingStrings(strings, queries):
for i in range(len(queries)):
query_to_match = '\'%s\'' % queries[i]
n_matches = strings.count(query_to_match)
print(n_matches)
matchingStrings(strings,queries)
當前 Output:
0
0
0
預期 Output:
2
1
0
這將通過使用正則表達式來工作,盡管它遍歷兩個列表時速度較慢:
def matching_strings(strings, queries):
for query in queries:
count = 0
for string in strings:
if re.match(query.strip(), string):
count += 1
print(count)
在您的輸入上運行 function 將提供所需的輸出! 這通過檢查查詢字符串是否匹配(不帶空格.strip()
)來工作。
這是我的 output:
>>> strings = ['ab', ' ab', 'abc']
>>> queries = ['ab', ' abc', ' bc']
>>> matching_strings(strings, queries)
2
1
0
所以這個解決方案接近正確的答案,但有一些事情正在發生。 首先,要將所有查詢與所有字符串進行比較,我們需要兩個 for 循環。 這是幫助可視化正在發生的事情的偽代碼:
如果您想看的話,這里是 python。
strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']
def matchingStrings(strings, queries):
for query in queries:
count = 0
# need to iterate through ALL strings.
for string in strings:
if query.strip() == string.strip():
count += 1
print(count)
matchingStrings(strings, queries)
使用 output:
2
1
0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.