python - 比较嵌套列表的相似度

标签 python python-3.x list comparison nested-lists

我有一个包含 3 个列表的列表,每个列表中都有 1 个列表。

data_set = [
    ['AB12345',['T','T','C','C','A','C','A','G','C','T','T','T','T','C']],
    ['AB12346',['T','T','C','C','A','C','C','G','C','T','C','T','T','C']],
    ['AB12347',['T','G','C','C','A','C','G','G','C','T','T','C','T','C']]
]

我有一个比较方法,可以给出包含字符的列表的相似性,而不是 id。

def compare(_from, _to):
    similarity = 0
    length = len(_from)
    if len(_from) != len(_to):
        raise Exception("Cannot be compared due to different length.")
    for i in range(length):
        if _from[i] == _to[i]:
            similarity += 1
    return similarity / length * 100

compare(data_set[0][1], data_set[1][1])

通过使用比较方法,我使用 for 循环将“a”列表与其他列表进行比较,如“a”与“a”比较、“a”与“b”比较、“a”与“C”。

for i in range(len(data_set)):
    data_set[i].append(compare(data_set[0][1], data_set[i][1]))
    print(round(data_set[i][2], 2), end=", ")

但是在完成第一个列表与其他列表及其本身的比较后,我如何循环到第二个列表和第三个列表并继续再次与其他列表进行比较以获得它们的相似性?例如,(“b”与“a”比较,“b”与“b”比较,“b”与“c”比较)和(“c”与“a”比较,“c”与“b”比较, “c”与“c”比较)。

最佳答案

为了将来引用,最好在代码中包含输入列表(a、b、c),而不是使用屏幕截图来避免人们必须键入整个列表。我使用了一些较短的版本进行测试。

您可以执行类似以下操作来迭代两个列表并比较结果。这比使用 for i in range(len(data_set)): 更简洁

# Make some test data
a= ["ID_A", ['T', 'G', 'A']]
b= ["ID_B", ['T', 'C', 'A']]
c= ["ID_C", ['C', 'A', 'A']]

data = [a,b,c]

# entry1 takes each of the values a,b,c in order, and entry2 will do the same,
# so you'll have all possible combinations.
for entry1 in data:
    for entry2 in data:
        score = compare(entry1[1], entry2[1])
        print("Compare ", entry1[0], " to ", entry2[0], "Score :", round(score))

输出:

Compare  ID_A  to  ID_A  Score : 100
Compare  ID_A  to  ID_B  Score : 67
Compare  ID_A  to  ID_C  Score : 33
Compare  ID_B  to  ID_A  Score : 67
Compare  ID_B  to  ID_B  Score : 100
Compare  ID_B  to  ID_C  Score : 33
Compare  ID_C  to  ID_A  Score : 33
Compare  ID_C  to  ID_B  Score : 33
Compare  ID_C  to  ID_C  Score : 100

您最好将分数存储在与保存列表的数组不同的数组中。

关于python - 比较嵌套列表的相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53228600/

相关文章:

java - 将 2 个数组列表合并为一个

list - scala:从列表生成元组

Pythonic 方式 : Utility functions in class or module

python-3.x - 在 Python 中将值插入字符串

python - 如何删除groupby的最后一行

python - Python 3.x 中的字典采样

python-3.x - 使用 asyncio 实现类似选择的功能

html - 更改 li 类再订购列表

python - 如何使用 Matplotlib 从现有轴执行子图

python - hasattr() 与 try-except block 处理不存在的属性