2017-04-16 81 views
0

問題:下面的基本數學公式是如何與python3相交和聯合計算不起作用的?Python3集,字符串列表的交集和聯合

LEN(Q1)+ LEN(Q2) - 路口=工會

輸入

q1 = ['How', 'does', 'the', 'Surface', 'Pro', 'himself', '4', 'compare', 'with', 'iPad', 'Pro', '?'] 
q2 = ['Why', 'did', 'Microsoft', 'choose', 'core', 'm3', 'and', 'not', 'core', 'i3', 'home', 'Surface', 'Pro', '4', '?'] 

intersect = set(q1).intersection(q2) 
union_length = list(set(q1).union(q2)) 

print('q1_len',len(q1)) 
print('q2_len',len(q2)) 
print('union',len(union_length)) 
print('intersect',len(intersect)) 

輸出

q1_len 12 
q2_len 15 
union 21 
intersect 4 

12 + 15 - 4應該是23不21.

回答

2

T他的規則適用於沒有設置列表中,因此,如果您打印:

print('q1_len',len(set(q1))) 
print('q2_len',len(set(q2))) 
print('union',len(union_length)) 
print('intersect',len(intersect)) 

輸出:

('q1_len', 11) 
('q2_len', 14) 
('union', 21) 
('intersect', 4) 

公式(11 + 14 - 4 = 21)成立。

+1

這是正確的,忘記獲取該集的len不是列表。 – user2263572