简体   繁体   中英

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?

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.

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.

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. 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:

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 = 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:

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 :

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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