简体   繁体   English

Python3集合,相交和字符串列表的并集

[英]Python3 Sets, Intersect and Union of list of strings

Question: How come the following basic math formula is not working with the python3 intersect and union calculation? 问题:以下基本数学公式为什么不能与python3相交和并集计算一起使用?

len(q1) + len(q2) - intersection = union len(q1)+ len(q2)-交集=并集

Input 输入

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

output 产量

q1_len 12
q2_len 15
union 21
intersect 4

12 + 15 - 4 should be 23 not 21. 12 + 15-4应该是23而不是21。

The rule applies to set not list, so if you print: 该规则适用于“设置不列出”,因此如果您打印:

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

Output: 输出:

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

The formula (11 + 14 - 4 = 21) holds true. 公式(11 + 14-4 = 21)成立。

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

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