Python – 提取当前、非索引匹配字符串的索引
给定两个字符串,从字符串1 中提取其他字符串中存在但不在同一索引中的所有字符的索引。
Input : test_str1 = ‘pplg’, test_str2 = ‘pineapple’
Output : [0, 1, 2]
Explanation : ppl is found in 2nd string, also not on same index as 1st.
Input : test_str1 = ‘pine’, test_str2 = ‘pineapple’
Output : []
Explanation : Found in other string on same index.
方法 #1:使用 enumerate() + 循环
在这种情况下,我们使用嵌套循环来检查每个字符在第二个字符串中的出现,然后如果它在其他位置,如果找到则附加索引。
Python3
# Python3 code to demonstrate working of
# Extract indices of Present, Non Index matching Strings
# using loop + enumerate()
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# the replaced result
res = []
for idx, val in enumerate(test_str1):
# if present in string 2
if val in test_str2:
# if not present at same index
if test_str2[idx] != val:
res.append(idx)
# printing result
print("The extracted indices : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract indices of Present, Non Index matching Strings
# using enumerate() + zip() + list comprehension
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# one-liner to solve this problem.
res = [idx for idx, (x, y) in enumerate(zip(test_str1, test_str2)) if x != y and x in test_str2]
# printing result
print("The extracted indices : " + str(res))
输出
The original string 1 is : apple
The original string 2 is : pineapple
The extracted indices : [0, 1, 2, 3, 4]
方法 #2:使用 enumerate() + zip() + 列表理解
在此,我们使用 enumerate() 执行获取索引的任务,并使用 zip() 完成两个字符串的配对,使用列表推导进行条件检查。
Python3
# Python3 code to demonstrate working of
# Extract indices of Present, Non Index matching Strings
# using enumerate() + zip() + list comprehension
# initializing strings
test_str1 = 'apple'
test_str2 = 'pineapple'
# printing original Strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# one-liner to solve this problem.
res = [idx for idx, (x, y) in enumerate(zip(test_str1, test_str2)) if x != y and x in test_str2]
# printing result
print("The extracted indices : " + str(res))
输出
The original string 1 is : apple
The original string 2 is : pineapple
The extracted indices : [0, 1, 2, 3, 4]