如何比较数组的两个索引(不是这些索引的值)?

Posted

技术标签:

【中文标题】如何比较数组的两个索引(不是这些索引的值)?【英文标题】:How to compare two indexes of an array (not values of these indexes)? 【发布时间】:2019-08-24 00:45:42 【问题描述】:

我需要制作一个程序来定义单词是否是字谜。好吧,这是我的代码。标有## here 的行反映了主要问题。我需要定义第一个和第二个for 循环的word1word2 的索引,然后比较它们。如果这些索引相似,则程序会遗漏该单词(因为它在迭代时出现两次)。我知道了,代码还没写完

text_sample = 'text goes here'

c = 0
i = 0
isanagramma = 0
n = len(text_sample)
while c < len(text_sample):
    for word1 in text_sample:
        for word2 in range(1,n):
            s1 = sorted(word1)
            s2 = sorted(text_sample[word2])
            index1 = text_sample.index(word1)                ## here
            index2 = text_sample.index(text_sample[word2])   ## here
            if index1 == index2:                             ## here
                continue                                     ## here
            if s1 == s2:
                isanagrama+=1
            i+=1
    c+=1
print(isanagramma)

【问题讨论】:

我不清楚,你有一串空格分隔的“单词”,你想比较所有单词,看看你是否有字谜?为您的text_sample 输入提供所需的输出 我在标记行之前的行中看到了几个问题。我建议您应该调试它以查看每个变量中的内容。然后,我建议您应该创建一个可验证的示例。见***.com/help/mcve text_sample 包含一些文本,其中我必须找到字谜(我正在将类型转换为列表) 如果一个字符串是字谜或不是 - 相对于另一个字符串进行检查。你能解释一下 - I must find anagrams 是什么意思吗?正如@Chris_Rands 所说 - 如果您为给定输入提供预期输出会更好 例如text_sample = 'The section number five of the contract contained the notices about the terms of delivery'“section”和“notices”这两个字是字谜,输出一定是这样section-notices 【参考方案1】:
text_sample = 'text goes here ttex'

s = text_sample.split(" ")
isanagramma = 0
for i in range (0,len(s)-1):
    for x in range(i+1,len(s)):
        if sorted(s[i]) == sorted(s[x]):
            print ("is anagram : and ".format(s[i],s[x]))
            isanagramma += isanagramma 
        else:
            print ("not anagram : and ".format(s[i],s[x]))

print (isanagramma)

输出:

not anagram :text and goes
not anagram :text and here
is anagram :text and ttex
not anagram :goes and here
not anagram :goes and ttex
not anagram :here and ttex
1

【讨论】:

以上是关于如何比较数组的两个索引(不是这些索引的值)?的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS forEach 比较下一个索引数组

如何比较两个熊猫数据框并返回将它们相互映射的索引?

比较python中的两个列表并返回匹配值的索引

JS-两个空数组为什么不相等?

JS-两个空数组为什么不相等?

两个空对象(空数组)为什么不相等