【问题标题】:Return index of differences when comparing uneven length strings比较长度不等的字符串时返回差异索引
【发布时间】:2020-12-07 13:15:44
【问题描述】:

我正在比较两个字符串,例如,'beacon' 和 'becon'。我本质上希望函数告诉我,在“信标”的索引 2 处,以列表的形式存在差异。我目前拥有的是:

word1 = 'beacon'
word2 = 'becon'
list = []

for i in range(len(word1)):
    if word1[i] != word2[i]:
        list.append(i)
return list

但我得到IndexError: string index out of range,因为 word1 比 word2 长。切换单词不是一种选择,因为如果我将像“beconn”这样的字符串与“becon”进行比较,我希望我的程序返回索引 5。我怎么能在不导入任何东西的情况下解决这个问题?

(理想情况下,该解决方案也适用于偶数长度的字符串(例如,将 'becon' 与 'bacon' 进行比较),如果存在多个差异,则返回索引列表。)

编码新手,非常感谢看到这个的人!

【问题讨论】:

  • 你的预期输出是什么?

标签: python python-3.x indexing comparison


【解决方案1】:

使用zip()zip_longest() 来满足两个str 的不均匀长度:

word1 = 'beacon'
word2 = 'becon'
chrs_lst = []
indx_lst = []

for indx, (w1, w2) in enumerate(zip(word1, word2)):
    if w1 != w2:
        chrs_lst.append(w1)
        indx_lst.append(indx)
        
print(chrs_lst)
print(indx_lst)

输出:

['a', 'c', 'o', 'n']                                                                                                                                                         
[2, 3, 4, 5] 

【讨论】:

  • 操作想要索引位置,所以如果你想避免,你必须使用枚举
  • ^已编辑,添加了字符和索引列表。
  • @DirtyBit 非常感谢你,很抱歉没有回答!我整晚都在研究这个问题,在发布这个问题后崩溃了,这真的很有帮助,我真的很感激!
  • @Serena 不用担心,发生在我们所有人身上。很高兴它有帮助! ^^
猜你喜欢
  • 2018-07-24
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多