【问题标题】:How to compare two lists and determine if they have common string elements? [closed]如何比较两个列表并确定它们是否具有共同的字符串元素? [关闭]
【发布时间】:2021-02-24 22:45:56
【问题描述】:

我有域名列表:

domains_1 = ['google.com', 'payments-amazon.com']
domains_2 = ['https://static-eu.payments-amazon.com/OffAmazonPayments/de/lpa/js/Widgets.js']

在这种情况下,payments-amazon.com 是公共域。考虑到域名可能又长又独特,我该如何找到它?

我已经尝试过了,但这仅在域准确的情况下才有效。如果它们在列表/字符串中包含部分域,我需要它们匹配:

matches = (set(domains_1).intersection(domains_2))
print(matches)

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 并不打算取代现有的文档和教程。重复你的弦乐教程;查找有关子字符串检查的部分。如果遇到困难,请在字符串列表中搜索子字符串。
  • 似乎嵌套循环是不可避免的:for short in domains_1: for long in domins_2: if short in long: print(long)
  • 您需要从每个列表元素中提取域,以便将它们相互比较。

标签: python comparison string-comparison


【解决方案1】:

您可以使用 tldextract 之类的包 - 除了在 AWS lambda 设置中之外,它的效果很好。或者您可以使用类似的方法从您的 URL 获取域。

def extract_domain(url):
    from urllib.parse import urlparse
    parsed_domain = urlparse(url)
    domain = parsed_domain.netloc or parsed_domain.path # Just in case, for urls without scheme
    domain_parts = domain.split('.')
    if len(domain_parts) > 2:
        return '.'.join(domain_parts[-(2 if domain_parts[-1] in {
            'com', 'net', 'org', 'io', 'ly', 'me', 'sh', 'fm', 'us'} else 3):])
    return domain

for x in domains_2:
    dom = extract_domain(x)
    if dom in domains_1:
        do your thing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多