我是 Python 新手。如何比較兩個不同長度的串列?如果兩個字符不匹配,我想列印“替換”,如果第二個串列字符為空,我想列印“洗掉”,如果第一個串列字符為空,我想列印“插入”。
str1 = "ANNA"
str2 = "ANA"
list1 = list(str1)
list2 = list(str2)
for i in range(len(list1)):
if list1[i] != list2[i]:
print("substitute")
elif len(list2[i]) == 0:
print("insert")
else:
print("delete")
uj5u.com熱心網友回復:
修改當前腳本的方法是避免嘗試在 list2 末尾運行,因為這就是觸發錯誤的原因:
# Note, strings can be accessed like a list with []
str1 = "ANNA"
str2 = "ANA"
for i in range(min(len(str1), len(str2))):
if str1[i] != str2[i]:
print("substitute")
else:
print("delete")
for _ in range(max(0,len(str1)-len(str2))):
print("insert")
一個稍微更 Python-ic 的方式是請求寬恕而不是通過 try/catch 獲得許可:
for i, c1 in enumerate(str1):
try:
if c1 != str2[i]:
print("substitute")
else:
print("delete")
except IndexError:
print("insert")
或者如果你不喜歡例外,更簡潔的方法是使用一些 itertools。在這里,我將使用 zip_longest 在較短串列中沒有物件的情況下回傳 None
from itertools import zip_longest
for a, b in zip_longest(str1, str2):
if not b:
print("insert")
elif a == b:
print("delete")
else:
print("substitue")
uj5u.com熱心網友回復:
您需要檢查 str 作為順序容器的功能。
請檢查以下代碼。
str1 = "ANNA"
str2 = "ANA"
## you don't need to make str to list. str is a container
####list1 = list(str1)
####list2 = list(str2)
if not str1 and not str2 : # empty str is logically false
print('substitute')
else:
print( 'insert' if str2 else 'delete' )
## # followings can replace above print()
## if str2:
## print('insert')
## else:
## print('delete')
# you may need this function
if str2:
str1 = str2
else:
str1 = '' # this can remove all characters in str
## # this if statement is same with following line
## str1 = str2
##
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441599.html
