在 Python 中实现集合的差异

时间:2021-06-25 15:50:48

标签: python python-3.x set

背景:

我正在重构一个个人项目的代码,想知道在给定类型的场景中从另一个集合创建一个集合时,最好使用示例中的中间两个代码块中的哪一个。插入的具体条件和元素无关。

基本示例

import itertools

# Example set
mySet={(6,6), (6,7), (6,8), (7,6), (7,7), (7,8)}
# First implementation
symmetric=set()
for x in mySet:
    # Compare all for every element
    if (x[1],x[0]) not in mySet:
        # Append some reversed
        symmetric.add(x[::-1])
hold=symmetric
# Second implementation
symmetric=set()
for x in mySet:
    # Append all reversed
    symmetric.add(x[::-1])
# Compare all via the implied algorithm
symmetric-=mySet
# Illustrate that the sets are identical
print('The sets are identical.') if (hold==symmetric) else print('The sets are not identical.')

更复杂的例子

import itertools

# Example set
mySet={(6,6), (6,7), (6,8), (7,6), (7,7), (7,8)}
# First implementation
someSet=set()
# Demonstrates use of itertools in for loop
for (a,b) in itertools.combinations(mySet, 2):
    # Demonstrates initialization and/or assignment
    pair=(a[0],b[1])
    # Demonstrates possibility of multiple conditions
    if a[0]==b[0] and pair not in mySet:
        someSet.add(pair)
hold=someSet
# Second implementation
someSet=set()
for (a,b) in itertools.combinations(mySet, 2):
    pair=(a[0],b[1])
    if a[0]==b[0]:
        someSet.add(pair)
someSet-=mySet
# Illustrate that the sets are identical
print('The sets are identical.') if (hold==someSet) else print('The sets are not identical.')

问题:

  • 在这种情况下,实现究竟有何不同?

  • 当集合中有很多和/或数量时,应该在这种情况下使用哪个?

例如:

# First implementation
newSet=set()
for x in mySet:
    if pair not in setA and pair not in setB: # Given some setA and setB
        newSet.add(x[::-1])
hold=newSet
# Second implementation
newSet=set()
for x in mySet:
    newSet.add(x[::-1])
newSet=newSet-setA-setB # s1.difference(s2, s3)

0 个答案:

没有答案
相关问题