简体   繁体   English

与整数的元组比较

[英]Tuple Comparison with Integers

I am trying to do tuple comparison. 我正在尝试进行元组比较。 I expected 2 as a result, but this bit of code prints out 0. Why? 结果我预计2,但这段代码打印出来0.为什么?

tup1 = (1, 2, 3, 4, 5)
tup2 = (2, 7, 9, 8, 5)
count = 0

if tup1[0:5] == tup2[0]:
    count + 1
elif tup1[0:5] == tup2[1]:
    count + 1
elif tup1[0:5] == tup2[2]:
    count + 1
elif tup1[0:5] == tup2[3]:
    count + 1
elif tup1[0:5] == tup2[4]:
    count + 1
print(count)

You can do what you intend with a set intersection: 您可以使用集合交叉点执行您想要的操作:

len(set(tup1) & set(tup2))

The intersection returns the common items in both tuples: 交集返回两个元组中的公共项:

>>> set(tup1) & set(tup2)
{2, 5}

Calling len on the result of the intersection gives the number of common items in both tuples. 在交集的结果上调用len会给出两个元组中的公共项的数量。

The above will however not give correct results if there are duplicated items in any of the tuples. 但是,如果任何元组中存在重复项,则上述内容不会给出正确的结果。 You will need to do, say a comprehension, to handle this: 理解你需要做的是处理这个问题:

sum(1 for i in tup1 if i in tup2) # adds one if item in tup1 is found in tup2

You may need to change the order in which the tuples appear depending on which of them has the duplicate. 您可能需要更改元组出现的顺序,具体取决于哪些元组具有副本。 Or if both contain dupes, you could make two runs juxtaposing both tuples and take the max value from both runs. 或者,如果两者都包含dupes,则可以进行两次运行并置两个元组并从两次运行中获取最大值。

You are comparing one slice of one tuple (eg tup1[0:5]) to one element of the other one which happens to be an integer. 您正在将一个元组的一个片段(例如tup1 [0:5])与另一个元素的一个元素进行比较,这个元素恰好是一个整数。 Therefore, the result of the comparison will always result in "False". 因此,比较的结果将总是导致“假”。 To check, whether an element of tup2 is situated also in tup1 as well, you may use intersection or the following: 要检查tup2的元素是否也位于tup1中,您可以使用交集或以下内容:

if tup2[n] in tup1:
   ...

Your code fails as you are comparing a tuple to an integer, even if you use in as below you would still need to use += count + 1 does not update the count variable: 您将代码与整数进行比较时代码失败,即使您使用如下所示仍然需要使用+= count + 1不更新count变量:

count = 0

for ele in tup2:
    if ele in tup1:
        count += 1

You can do it in linear time and account for duplicate occurrences in tup2 making only tup1 set: 你可以在线性时间内完成它,并在tup2中考虑重复出现,只设置tup1:

st = set(tup1)
print(sum(ele in st for ele in tup2))

If you wanted the total sum from both of common elements, you could use a Counter dict : 如果你想要两个共同元素的总和,你可以使用Counter dict

tup1 = (1, 2, 3, 4, 5, 4, 2)
tup2 = (2, 7, 9, 8, 2, 5)
from collections import Counter

cn = Counter(tup1)

print(sum(cn[i] for i in tup2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM