Python:如何基于if条件实例化新的数据结构

时间:2017-06-15 02:29:28

标签: python data-structures

n =用户输入的总数,以2个整数的形式显示:x y
x y =空格分隔的整数输入

问题:
当我遍历n输入时,我希望根据条件(如果集合中已存在xy的条件)将每个输入放入不同的集合中,添加到其中。否则,请创建一个新集。

示例输入:

n = 4
1 2 
10 11
4 5
3 1

示例输出:

(1,2,3)
(4,5)
(10,11)

这就是我所拥有的:

t = set()
x,y = raw_input()
x,y = (int(x),int(y))
t.update([x,y])

for i in xrange(1,n):
    new_set = set()
    x,y = raw_input()
    x,y = (int(x),int(y))
    if x in t or y in t:
        t.update([x,y])
    elif x not in t and y not in t:
        new_set.update([x,y])

显然,这不起作用,因为new_set是在for_loop内定义的,每次看到一对新x y时,new_set都会被重置。

问题:
如何创建新集合,因为它们的创建取决于if-else条件,并且没有办法预先确定所需的集合总数,尤其是n变大?

2 个答案:

答案 0 :(得分:1)

这是未经测试的,因为我在平板电脑上。尽管如此,

# Python 3
# Should work equally well for Python 2.6+ by just replacing input with raw_input

def make_getter(type_):
    def get_type(prompt=""):
        while True:
            try:
                return type_(input(prompt))
            except ValueError:
                pass
    return get_type

get_int  = make_getter(int)
get_ints = make_getter(lambda s: [int(i) for i in s.split()])

def find_group(all_groups, n):
    for group in all_groups:
        if n in group:
            return group
    return None

def main():
    all_groups = set()     # set of frozenset of int
    num_inputs = get_int("How many input pairs? ")
    for _ in range(num_inputs):
        x, y = get_ints()
        x_group = find_group(all_groups, x)
        y_group = find_group(all_groups, y)
        if x_group is None and y_group is None:
            # create new group
            all_groups.add(frozenset([x, y]))
        elif x_group is None:
            # add x to existing y group
            all_groups.remove(y_group)
            all_groups.add(y_group | {x})
        elif y_group is None:
            # add y to existing x group
            all_groups.remove(x_group)
            all_groups.add(x_group | {y})
        elif x_group is y_group:
            #special case - x and y already belong to the same group
            pass
        else:
            # merge existing x group and y group
            all_groups.remove(x_group)
            all_groups.remove(y_group)
            all_groups.add(x_group | y_group)
    # show final result
    print(all_groups)

if __name__ == "__main__":
    main()

答案 1 :(得分:0)

维护您的集合列表,如下所示:

Python 3:

setList = []
n = 3

for i in range(n):
    x, y = input().split()
    x, y = int(x), int(y)
    for s in setList:
        if x in s or y in s:
            s.update({x,y})
            break
    else:
        setList.append({x,y})

Python 2:

setList = []
n = 3

for i in xrange(n):
    x, y = raw_input().split()
    x, y = int(x), int(y)
    for s in setList:
        if x in s or y in s:
            s.update({x,y})
            break
    else:
        setList.append({x,y})

正如Hugh Bothwell在对你的问题的评论中指出的那样,当输入每个数字属于不同集合的一对时,这个解决方案会遇到问题。