如何在Python中查找字符串的公共元素,但顺序不正确?

如何在Python中查找字符串的公共元素,但顺序不正确?,python,string,indexing,Python,String,Indexing,假设有两个字符串: str1 = "15323" str2 = "12314" 如何在两个字符串中找到基于其中一个字符串的顺序不相同的数字索引? 预期: [3, 4] # the numbers in str1 that are in str2 but not in the exact place of str2: 2 and 3 "15323" ^^ "12314" ^^ 另一个例子,因为我无法真正解释: str1 = "3546" str2 = "1346" 预期: [3,

假设有两个字符串:

str1 = "15323"
str2 = "12314"
如何在两个字符串中找到基于其中一个字符串的顺序不相同的数字索引? 预期:

[3, 4] # the numbers in str1 that are in str2 but not in the exact place of str2: 2 and 3
"15323"
    ^^
"12314"
  ^^
另一个例子,因为我无法真正解释:

str1 = "3546"
str2 = "1346"
预期:

[3, 4] # the numbers in str1 that are in str2 but not in the exact place of str2: 2 and 3
"15323"
    ^^
"12314"
  ^^
[0] # only "3" is in str1 AND str2 and it does not have the same index as the "3" in str2

"3546"
"3" in "3546" appears in str2 and it does not have the same index
"5" in "3546" does not appear in str2
"4" in "3546" appears in str1 but has the same index as the "4" in str2
"6" in "3546" appears in str1 but has the same index as the "6" in str2
我已经尝试了一些代码来寻找两个字符串中的公共元素,但是我不能完全理解重复的元素。我不想导入任何模块,并提前感谢您

result = []
for string in str1:
  if string in str2:
    if str1.index(string) != str2.index(string):
      result.append(str1.index(string))


使用
枚举
而不是
索引
查找索引<代码>索引将返回字符串中第一次出现的值

精炼代码

result = []
for idx,i in enumerate(str1):
    if i in str2:
        if str2[idx]!=i:      
            result.append(idx)

为了进行有效的成员资格测试,您可以将
str2
转换为一个集合,并枚举
str1
str2
的压缩序列,并且仅输出对应字符不相等且
str1
中的字符在集合中的索引:

s = set(str2)
[i for i, (a, b) in enumerate(zip(str1, str2)) if a != b and a in s]
因此,鉴于:

str1 = "15323"
str2 = "12314"
str1 = "3546"
str2 = "1346"
表达式将返回:

[3, 4]
[0]
鉴于:

str1 = "15323"
str2 = "12314"
str1 = "3546"
str2 = "1346"
它将返回:

[3, 4]
[0]

仔细检查你的第二个例子。您有“35”和“13”,预期的是
[0]
?为什么?预期为[0],因为有一个名为
result
列表,其中包含满足上述条件的子字符串的所有索引。在这种情况下,
str1[0]
“3”
,并且符合标准。对不起,如果我对这个问题的措辞不是很好,我的英语不是很好。索引是一个问题。我不认为
set
是解决这个问题的最佳和有效的方法。不,例如,如果我在str2:
中,代码中的
不必要地使时间复杂度为O(n^2)而不是O(n),这可以通过预先的set转换来实现。具体如何实现<代码>如果在str2中输入i:
在功能上与
s=set(str2)
如果在s中输入i:
完全相同,只是后者在循环中更有效。
中的
操作员不关心
str2
是否有重复项。顺便说一句,str2确实有重复项,如OP的第一个示例所示。