如何根据位置索引比较两个元组列表

2024-04-24 17:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

[('abc', 'bac'), ('cab', 'def')]

比较('abc', 'bac'),我们可以看到在第一个字符串abc中,ab的索引与第二个字符串bac不同,即ba,第二个索引是c,因此在2中是输出。你知道吗

('cab', 'def')

比较每个元素是不同的,所以out是3。你知道吗

检查位置的各项指标并取其差值

预计出局

[2, 3]

代码

    list_ = [('abc', 'bac'), ('cab', 'def')]

for i,j in list_:
    x = (list(zip(i,j)))
    print (list(zip(i,j)))

出去

[('a', 'b'), ('b', 'a'), ('c', 'c')]
[('c', 'd'), ('a', 'e'), ('b', 'f')]

如果添加

count = 0
for i,j in x:
    if i != j:
        count += 1
print (count)

我的输出是3,第一个差异2没有打印


Tags: 数据字符串in元素fordefcountzip
3条回答
list_ = [('abc', 'bac'), ('abc', 'def')]
print(list(a == b  for a, b in list_))

[False, False]


list_ = [('abc', 'bac'), ('abc', 'abc')]
print(list(a == b  for a, b in list_))

[False, True]

如果我答对了,你要计算每个字符串元组中不相等字母的数量,“不等”也意味着相对于字母在字符串中的位置不相等。你知道吗

因为很难直接用字母来计算,所以从计算机的角度想想它们是什么:数字!因此,对于list中的每个tuple,您可以将字符串中的每个字母转换为其integer表示形式,取差值并计算非零元素:

l = [('abc', 'bac'), ('cab', 'def')]

result = []
for t in l:
    delta = map(lambda x, y: ord(x)-ord(y), *t)
    result.append(sum(1 for i in delta if i))

# result
# Out[7]: [2, 3]

作为一条直线:

result = [sum(1 for i in map(lambda x, y: ord(x)-ord(y), *t) if i) for t in l]

如果我没看错你的意思,你会想要:

结果为[2,3],其中:

('abc', 'bac') = [1, 1, 0]#累计值变为最终值“2”。你知道吗

以及

('cab', 'def') = [1, 1, 1]#累计值变为最终值“3”。你知道吗

请参阅我的答案和下面的内联评论:

dataset = [('abc', 'bac'), ('cab', 'def')]

end_result = []

for item in dataset:                    # use of word dataset prevents confusion related
                                        # to lists (regardless of the use "_".)
    print (item)
    x = (list(zip(item[0], item[1])))

    local_result = []

    print (x)

    for i,j in x:
        if i == j:
            local_result.append(0)   # adding non value to equal "letters" in item.
        else:
            local_result.append(1)   # if not equal count "1".
    print (local_result)

    count_results = 0

    for value in local_result:       # check the outcome of the local result and summarize its
                                     # findings in an end_result list for each
                                     # item in the dataset.
        if value == 1:
            count_results += 1

    end_result.append(count_results)

    print ("End result: %s" % end_result)

print (end_result)          # prints the overal end result "2, 3"

输出:

[('a', 'b'), ('b', 'a'), ('c', 'c')]
[1, 1, 0]
End result: [2]
('cab', 'def')
[('c', 'd'), ('a', 'e'), ('b', 'f')]
[1, 1, 1]
End result: [2, 3]
[2, 3]```

相关问题 更多 >