
[英]match length of string with a string with the same length in a list
所以,如果我有这个: a = "hi" b = ["hello there", "goodbye", "nice to meet you"] 因此,如果len(a)为2,那么是否有可能在b中找到相同长度的字符串? 在这种情况下是“你好” 对于“ hi”,我是在数字符,对于“ ...
[英]How to match two list with the same length
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我有两个长度相同的列表。 我想在 df 和 df2 中找到匹配项。
df = [[[1, 5,7,9,12,13,17],
[2,17,18,23,32,34,45],
[3,5,11,33,34,36,45]],
[[6,21,22,50,56,58,72],
[7,5,12,13,55,56,74],
[8,23,24,32,56,58,64]]]
df2 = [[[100,5,12,15,27,32,54],
[120,10,17,18,19,43,55],
[99,21,32,33,34,36,54]],
[[41,16,32,45,66,67,76],
[56,10,11,43,54,55,56],
[77,12,16,18,19,21,23]]]
我希望我的 output 是这样的或类似的。
output = [[[[5,12,],[17]],
[[17,18],[32,34,36]]],
[[[55,56],[32]],[[56]]]
所以这个问题很难,因为你为了比较 arrays 你需要计算所有可能首先出现的序列。 所以当你处理大 arrays 时,这个任务会花费很长时间。
为了简单起见,我的方法没有以任何方式进行优化,我试图坚持使用基本的 for 循环,只是强行通过它。
首先,我将计算 arrays 的所有可能组合并将它们存储在两个列表( sequences_1
和sequences_2
)中。
之后,我将比较所有序列并将匹配项存储在一个集合中。 使用集合会自动删除所有重复项。 Matches
现在包含两个 arrays 的所有可能匹配项。
df = [
[[1, 5, 7, 9, 12, 13, 17], [2, 17, 18, 23, 32, 34, 45], [3, 5, 11, 33, 34, 36, 45]],
[[6, 21, 22, 50, 56, 58, 72], [7, 5, 12, 13, 55, 56, 74], [8, 23, 24, 32, 56, 58, 64]],
]
df2 = [
[[100, 5, 12, 15, 27, 32, 54], [120, 10, 17, 18, 19, 43, 55], [99, 21, 32, 33, 34, 36, 54]],
[[41, 16, 32, 45, 66, 67, 76], [56, 10, 11, 43, 54, 55, 56], [77, 12, 16, 18, 19, 21, 23]],
]
sequences_1 = []
for el in df:
for lis in el:
length = len(lis)
for i in range(0, length):
for n in range(i + 1, length + 1):
sequences_1.append(lis[i:n])
sequences_2 = []
for el in df2:
for lis in el:
length = len(lis)
for i in range(0, length):
for n in range(i + 1, length + 1):
sequences_2.append(lis[i:n])
matches = set()
for seq_1 in sequences_1:
for seq_2 in sequences_2:
if seq_1 == seq_2:
matches.add(tuple(seq_1))
print(matches)
作为比赛,我得到:
{(5,), (11,), (17,), (23,), (17, 18), (32,), (55, 56), (56,), (5, 12), (34, 36), (34,), (33, 34, 36), (55,), (33, 34), (12,), (18,), (21,), (33,), (36,), (45,)}
这包含您作为可能的 output 提供的所有匹配项,以及您在发布问题时错过的其他匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.