[英]Find the difference between two strings of uneven length in python
a = 'abcdfjghij'
b = 'abcdfjghi'
Output: j
def diff(a, b):
string=''
for val in a:
if val not in b:
string=val
return string
a = 'abcdfjghij'
b = 'abcdfjghi'
print(diff(a,b))
此代碼返回一個空字符串。 有什么解決辦法嗎?
標准庫中的collections.Counter
可用於 model 多組,因此它可以跟蹤重復的元素。 它是dict
的子類,它具有高性能並擴展了其功能以用於計數目的。 要找到兩個字符串之間的差異,您可以模仿集合之間的對稱差異。
from collections import Counter
a = 'abcdfjghij'
b = 'abcdfjghi'
ca = Counter(a)
cb = Counter(b)
diff = (cb-ca)+(ca-cb) # symmetric difference
print(diff)
#Counter({'j': 1})
如果我理解正確你的問題是:
“給定 2 個不同長度的字符串,我怎樣才能找到它們之間不同的字符?”
因此,根據您的示例判斷,這意味着您要么想要僅存在於字符串 1 中而不存在於另一個字符串中的字符,要么想要可能重復且兩個字符串之間的計數不同的字符。
這是一個簡單的解決方案(可能不是最有效的解決方案),但它很短且不需要任何額外的包:
**更新: **
a = 'abcdfjghij'
b = 'abcdfjghi'
dict_a = dict( (char, a.count(char)) for char in a)
dict_b = dict( (char, b.count(char)) for char in b)
idx_longest = [dict_a, dict_b].index(max([dict_a, dict_b], key = len))
results = [ k for (k,v) in [dict_a, dict_b][idx_longest].items() if k not in [dict_a, dict_b][1-idx_longest].keys() or v!=[dict_a, dict_b][1-idx_longest][k] ]
print(results)
> ['j']
或者您可以嘗試使用其他一對字符串,例如
a = 'abcaa'
b = 'aaa'
print(results)
> ['b', 'c']
因為'a'在兩個字符串中的次數相等。
更新
但是你在 a 中有兩次 j。 所以它第一次看到 j 時,它會看到 b 並看到 aj,一切都很好。 對於第二個 j,它再次查看並且仍然看到 aj,一切都很好。 您是否要檢查每個字母是否與同一序列中的另一個字母相同,那么您應該嘗試以下操作:
a = 'abcdfjghij'
b = 'abcdfjghi'
def diff(a, b):
if len(a)>len(b):
smallest_len = len(b)
for index, value in enumerate(a[:smallest_len]):
if a[index] != b[index]:
print(f'a value {a[index]} at index {index} does not match b value {b[index]}')
if len(a) == len(b):
pass
else:
print(f'Extra Values in A Are {a[smallest_len:]}')
else:
smallest_len = len(a)
for index, value in enumerate(b[:smallest_len]):
if a[index] != b[index]:
print(f'a value {a[index]} at index {index} does not match b value {b[index]}')
if len(a) == len(b):
pass
else:
print(f'Extra Values in B Are {b[smallest_len:]}')
diff(a, b)
在您的示例中,兩個字符串之間有 2 個區別:字母 g 和 j。 我測試了您的代碼,它返回 g,因為來自的所有其他字母都在 b 中:
a = 'abcdfjghij'
b = 'abcdfjhi'
def diff(a, b):
string=''
for val in a:
if val not in b:
string=val
return string
print(diff(a,b))
根據您的問題,很難確切知道您想要什么。 喜歡應該
'abc'
'efg'
return 'abc' 或 'efg' 還是總是只添加一個字符?
這是一個解決方案,它解釋了多個不同的字符,但仍然可能無法給出您的確切 output。
def diff(a, b):
string = ''
if(len(a) >= len(b)):
longString = a
shortString = b
else:
longString = b
shortString = a
for i in range(len(longString)):
if(i >= len(shortString) or longString[i] != shortString[i]):
string += longString[i]
return string
a = 'abcdfjghij'
b = 'abcdfjghi'
print(diff(a,b))
如果一個字符串只添加了一個字符,並且 i 可以在字符串中的任何位置,您可以更改
string += longString[i]
至
string = longString[i]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.