简体   繁体   English

多套并集的语法

[英]Syntax of union of several sets

I would like to understand why is this a valid syntax: 我想了解为什么这是一种有效的语法:

common = (set(classes['Biology']) & set(classes['Math']) & set(classes['PE']) & set(classes['Social Sciences']) & set(classes['Chemistry']))

but not this: 但不是这个:

common = set(classes['Biology']) & set(classes['Math']) & set(classes['PE'] & set(classes['Social Sciences']) & set(classes['Chemistry'])

TL;DR TL; DR

Why is there a need to put all the unions into normal braces 为什么需要将所有的工会放在正常的括号中

() ()

Thank you. 谢谢。

The second one is invalid because it's missing a close paren on set(classes['PE'] . You don't need the outer parentheses, you just need to close the inner ones correctly. 第二个无效,因为它缺少set(classes['PE']上的封闭括号。您不需要外部括号,只需要正确地封闭内部括号即可。

Side-note: Performance-wise, you'd likely save a little by only explicitly converting the first item to a set , then using the intersection (which takes an arbitrary number of iterable arguments) to do the rest of the work in a single Python function call: 旁注:从性能角度来看,您可能会节省一点,方法是仅将第一个项目显式转换为set ,然后使用intersection (需要任意数量的可迭代参数)在单个操作中完成其余工作Python函数调用:

common = set(classes['Biology']).intersection(classes['Math'], classes['PE'], classes['Social Sciences'], classes['Chemistry'])

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

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