簡體   English   中英

在遍歷列表時搜索字符串

[英]Search for strings while iterating through a list

我有一個非常簡單的 Python 腳本/任務,我試圖在迭代列表時搜索文本字符串。

domains = ['google.com', 'facebook.com', 'cnn.com']
domain = []

for x in domains:
  if any("google"):
    domain.append("Google")

上面代碼的 output 是: ['Google', 'Google', 'Google'] 我希望 output 只有一個“Google”條目,因為只有一個域可以匹配。

我試過了

re.search('google',x)

和:

for x in domains:
  if any("google" in x for x in domains):
    domain.append("Google")

每個的 output 是相同的。 只要整個列表中有一個“Google”條目,那么每個 append 條目將是“Google”。 我很抱歉,因為我確定這是一個簡單的問題,但我似乎無法正確理解它。 這是我項目的最后一部分,我很難過。 任何幫助表示贊賞。

您的問題是您正在將domains列表中的所有條目與google進行比較,而不僅僅是當前條目:

domains = ['google.com', 'facebook.com', 'cnn.com']
domain = []

for d in domains:
    if 'google' in d:
        domain.append('Google')

Output

['Google']
domains = ['google.com', 'facebook.com', 'cnn.com'] domain = [] for x in domains: if "google" in x: domain.append("Google")

以下是三種有效的方法:

domains = ['google.com', 'facebook.com', 'cnn.com', 'www.google.com']

# Approach 1: regex
matching_domains = []
for x in domains:
  if re.search('google', x):
    matching_domains.append(x)
print(matching_domains)

# Approach 2: `in`
matching_domains = []
for domain in domains:
  if "google" in domain:
    matching_domains.append(domain)
print(matching_domains)

# Approach 3: `filter`
# - see https://docs.python.org/3/library/functions.html#filter
# - see https://www.geeksforgeeks.org/filter-in-python/
matching_domains = []
matching_domains = filter(lambda x: "google" in x, domains)
print(matching_domains)

您使用re (regex) 的方法非常接近。 祝你的項目好運。 希望你堅持軟件開發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM