如何传递2套作为函数的参数?

时间:2019-02-18 06:52:25

标签: python python-3.x

创建一个Python程序,要求用户输入两组以逗号分隔的值。使用字符串split()方法解析该行,然后使用set()函数隐式设置要设置的列表。通过将两个集合及其彼此的关系显示为子集,超集,并集,交集和差来论证两个集合的集理论。

我不确定如何在函数中传递两个集合吗?

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

TypeError:设置期望的最多1个参数,得到4个

3 个答案:

答案 0 :(得分:1)

您应将其转换为set,然后将其传递给

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

答案 1 :(得分:0)

这是解决方案之一。

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}
'''

答案 2 :(得分:0)

set类采用一个数组进行初始化,但是您提供了多个整数。将您的代码更改为

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

解决您的问题