在不同长度的字符串中查找不同的字符

2024-09-30 01:37:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码来找出字符串之间的差异。目前,它适用于相同长度的字符串,但我正试图让它适用于不同长度的字符串。我该怎么做

我添加了一个新变量longest_seq来尝试解决这个问题,但我不知道如何使用它。你知道吗

ref_seq = "pandabears"
map_seq = "pondabear"
longest_seq = map_seq

if len(ref_seq) > len(map_seq):
    longest_seq == ref_seq


for i in range(len(longest_seq)):
    if ref_seq[i] != map_seq[i]: 
        print i, ref_seq[i], map_seq[i]

Tags: 字符串代码inrefmapforlenlongest
2条回答

像这样的东西应该能奏效。你知道吗

def different_characters(reference, target):
    # So we don't accidentally index the shorter string past its ending
    ending = min(len(reference), len(target))

    for i in range(ending):
        if reference[i] != target[i]:
            print(i, reference[i], target[i])

    longer_str = reference if len(reference) > len(target) else target
    for i in range(ending, len(longer_str)):
        print(i, longer_str[i], '<empty>')


different_characters('pandabears', 'pondabear')

将打印:

1 a o
9 s <empty>

对于Python2,可以使用itertools.izip来实现:

from itertools import izip

for i, j in izip(ref_seq, map_seq):
    if i != j: 
        print i, j

输出:

a o

在Python 3中,可以使用内置的zip函数:

for i, j in zip(ref_seq, map_seq):
    if i != j: 
        print(i, j)

zip存在于Python 2中,但建议使用itertools.izip,因为它在需要时生成元组(在每次迭代中都生成一个新元组),而不是一次生成所有元组,在Python 3中,zip执行Python 2中itertools.izip所执行的操作。你知道吗

相关问题 更多 >

    热门问题