Python 如何将两个集合作为函数的参数传递?

Python 如何将两个集合作为函数的参数传递?,python,python-3.x,Python,Python 3.x,创建一个Python程序,要求用户输入两组逗号分隔的值。使用stringsplit方法解析该行,然后使用set函数将列表转换为set。通过将两个集合及其相互关系显示为子集、超集、并集、交集和差分来演示这两个集合的集合论 我不知道如何在一个函数中传递两个集合 print(two_set(set(1,2,3,4), set(2,3,4,5,6))) TypeError:设置最多需要1个参数,得到4个 应将其转换为集合,然后传递: def two_set(set_a, set_b):

创建一个Python程序,要求用户输入两组逗号分隔的值。使用stringsplit方法解析该行,然后使用set函数将列表转换为set。通过将两个集合及其相互关系显示为子集、超集、并集、交集和差分来演示这两个集合的集合论

我不知道如何在一个函数中传递两个集合

print(two_set(set(1,2,3,4), set(2,3,4,5,6)))
TypeError:设置最多需要1个参数,得到4个


应将其转换为集合,然后传递:

def two_set(set_a, set_b):
        return (set_a, set_b)


set_a = set([1,2,3,4])
set_b = set([2,3,4,5,6,6,6,6])

print(two_set(set_a, set_b))
输出:

({1, 2, 3, 4}, {2, 3, 4, 5, 6})

这是解决办法之一

class Settherory:
    def __init__(self, set1,set2):
        self.set1 = set1
        self.set2=set2
    def subset(self):
        if self.set1.issubset(self.set2):
            return '{} is subset of {}'.format(self.set1,self.set2)
        elif self.set2.issubset(self.set1):
            return '{} is subset of {}'.format(self.set2,self.set1)
        else:
            return 'not a subset'

    def superset(self):
        if self.set1.issuperset(self.set2):
            return '{} is superset of {}'.format(self.set1,self.set2)
        elif self.set2.issuperset(self.set1):
            return '{} is superset of {}'.format(self.set2,self.set1)
        else:
            return 'not a superset'
    def union(self):
        return 'union of sets is {}'.format(self.set1 | self.set2)

    def difference(self):
        return 'difference of set is {}'.format(self.set1 - self.set2)

    def intersection(self):
        return 'intersection of two sets is {}'.format(self.set1 & self.set2)



set_1 = set(map(int,input('enter the data in set 1 ').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2').strip().split(',')))

x= Settherory(set_1, set_2)
print(x.subset(), x.difference(), x.superset(),x.union(),x.intersection(),sep='\n')


'''
enter the data in set 1 1,2,3,4,5

enter the data in set 23,4,5
{3, 4, 5} is subset of {1, 2, 3, 4, 5}
difference of set is {1, 2}
{1, 2, 3, 4, 5} is superset of {3, 4, 5}
union of sets is {1, 2, 3, 4, 5}
intersection of two sets is {3, 4, 5}
'''
另一种方法是

# take input as single line seperated by ','
set_1 = set(map(int,input('enter the data in set 1 :').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2 : ').strip().split(',')))

# for finding the subset or other set operation you can use direct inbuilt function on set like:

print(set_1.issubset(set_2))
print(set_1.issuperset(set_2))
print(set_1.union(set_2))
print(set_1.difference(set_2))

# output 
'''
enter the data in set 1 : 1,2,3,4

enter the data in set 2 : 2,3
False
True
{1, 2, 3, 4}
{1, 4}
'''

set类接受一个数组进行初始化,但您将改为提供多个整数。将代码更改为

print(two_set(set([1,2,3,4]), set([2,3,4,5,6])))

要解决您的问题

您可以发布two_set的功能吗?发布two_set方法。首先创建集合,然后调用two_set1,set2。如错误所示,您需要设置您的_list而不是set1,2,3,4使用set[1,2,3,4]而不是set1,2,3,4。