gpt4 book ai didi

python - 查找两个列表中不包含公共(public)字符的所有字符串对

转载 作者:行者123 更新时间:2023-12-03 15:48:02 25 4
gpt4 key购买 nike

我有两个字符串列表,并希望在它们之间找到所有不包含公共(public)字符的字符串对。例如

list1 = ['abc', 'cde']
list2 = ['aij', 'xyz', 'abc']

desired output = [('abc', 'xyz'), ('cde', 'aij'), ('cde', 'xyz')]
我需要它尽可能高效,因为我正在处理包含数百万个字符串的列表。
目前,我的代码遵循以下一般模式:
output = []

for str1 in list1:
for str2 in list2:
if len(set(str1) & set(str2)) == 0:
output.append((str1, str2))
这是 O(n^2) 并且需要很多小时才能运行,有人对如何加快速度有一些建议吗?也许有一种方法可以利用每个正在排序的字符串中的字符?
非常感谢您!

最佳答案

这是另一种方法,专注于将集合操作降低为位旋转和组合表示同一组字母的单词:

import collections
import string


def build_index(words):
index = collections.defaultdict(list)
for word in words:
chi = sum(1 << string.ascii_lowercase.index(letter) for letter in set(word))
index[chi].append(word)
return index


def disjoint_pairs(words1, words2):
index1 = build_index(words1)
index2 = build_index(words2)
for chi1, words1 in index1.items():
for chi2, words2 in index2.items():
if chi1 & chi2:
continue
for word1 in words1:
for word2 in words2:
yield word1, word2


print(list(disjoint_pairs(["abc", "cde"], ["aij", "xyz", "abc"])))

关于python - 查找两个列表中不包含公共(public)字符的所有字符串对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64078394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com