【问题标题】:Checking the same elements in a list : python检查列表中的相同元素:python
【发布时间】:2015-12-08 04:33:58
【问题描述】:

嘿,我在编码方面太新了,我想让程序比较两个列表元素并返回其中的相同元素。 到目前为止,我编写了这段代码,但我遇到了算法问题,因为它是设置操作,我找不到具有交集函数的实际相同元素。

在我的代码中,我想查找每个字符串并找到它们的相似性。 我试图做的是:

    input="AGA"
    input1="ACA"
    input=input_a
    if len(input1) == len(input):
        i = 0
        while i < len(input1):
            j = 0
            while j < len(input_a):
                input_length = list(input_a)
                if input1[i] != input_a[j]:
                    if input1[i] in input_a:
                        print "1st %s" % input_length
                        print "2nd %s" % set(input1)
                        intersection = set(DNA_input_length).intersection(set(input1))
                        print intersection
                        total = len(intersection)
                        print (float(total) / float(
                            len(input1))) * 100, "is the similarity percentage"
                        break

                    DNA_input_length.remove(input_a[i])
                j = j + 1
            break

我的代码有什么问题实际上是我猜的交叉部分 我想将输入和 input1 = A,A (2 A's both) 视为每个列表中包含的公共元素,但是,我只得到一个 A.. 我如何改进此代码以评估两个 A 不是一个的常见元素。我真的需要你的帮助..

【问题讨论】:

    标签: python list recursion while-loop set


    【解决方案1】:

    我将相似度定义为单词之间的汉明距离(我认为这就是你想要的

    word1 = "AGA"
    word2 = "ACAT"
    score = sum(a==b for a,b in zip(word1,word2)) + abs(len(word1)-len(word2))
    

    【讨论】:

    • 嘿,就是这样!如果你愿意,我可以再问一个问题吗.. 如果有一种方法可以寻找与 while 循环的相似性,我真的很想知道它..:)
    【解决方案2】:

    如果您只需要找到 2 个平面列表的相交元素,请执行以下操作:

    a = "AGA"
    b = "ACA"
    c = set(a) & set(b)
    print(c)
    > {'A'}
    

    【讨论】:

    • 嘿,谢谢菲利克斯的回答!但是,我希望在 AGA 和 ACA 中作为 [A,A] 的交集
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2012-08-22
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多