Python 整数元组比较
我正在尝试做元组比较。我期望结果是2,但这段代码输出0。为什么?Python 整数元组比较,python,integer,comparison,tuples,Python,Integer,Comparison,Tuples,我正在尝试做元组比较。我期望结果是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 +
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)
您可以使用设置的交点执行您想要的操作:
len(set(tup1) & set(tup2))
交集返回两个元组中的公共项:
>>> set(tup1) & set(tup2)
{2, 5}
对交集的结果调用len
,可以得到两个元组中的公共项数
但是,如果任何元组中存在重复项,则上述方法将不会给出正确的结果。你需要做,比如说理解,来处理这个问题:
sum(1 for i in tup1 if i in tup2) # adds one if item in tup1 is found in tup2
您可能需要更改元组的显示顺序,具体取决于哪个元组具有重复项。或者,如果两个元组都包含重复项,则可以将两个元组并列运行两次,并从两次运行中获取最大值。您正在将一个元组的一个片段(例如,tup1[0:5])与另一个元组的一个元素(恰好是整数)进行比较。因此,比较的结果总是“假”。 要检查tup2的元素是否也位于tup1中,可以使用交叉点或以下选项:
if tup2[n] in tup1:
...
当您将元组与整数进行比较时,代码失败,即使您在下面的中使用,您仍然需要使用
+=
count+1
不更新count变量:
count = 0
for ele in tup2:
if ele in tup1:
count += 1
您可以在线性时间内执行此操作,并考虑tup2中重复出现的情况,仅设置tup1:
st = set(tup1)
print(sum(ele in st for ele in tup2))
如果需要两个公共元素的总和,可以使用计数器指令:
所有测试都不会通过。类型tuple永远不会等于int
tup[0:5]
是一个tuple。它永远不会等于整数。所以你要做两个元组的交集并计算共有多少个值?使用set
噢,我明白了,你可能会更走运。非常感谢你!
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))