TypeError: list indices must be integers, not set Python

TypeError: list indices must be integers, not set Python

我在这里要做的是将集合列表作为输入,return 一组出现在所有给定集合中的元素。我收到 'TypeError: list indices must be integers, not set' 错误。我不明白为什么会这样,因为 range(len(list_of_sets)) 是一个整数列表。

def intersection_of_sets(list_of_sets):
    return reduce(lambda x, y: list_of_sets[x] &\
    list_of_sets[y], range(len(list_of_sets)))

print(intersection_of_sets([{1, 2, 3}, {2, 3, 4}, {2, 5}, {1, 2, 5}]))

我想要的输出是 set([2])

问题出现在 reduce() 操作的第二个 iteration/step 上,因为第一个 iteration/step 产生了一个集合:

list_of_sets[0] & list_of_sets[1]  # returns a set 

调试一下就可以观察到,打印出xy的值:

def intersection_of_sets(list_of_sets):
    def merge_function(x, y):
        print(x, y)
        return list_of_sets[x] & list_of_sets[y]

    return reduce(merge_function, range(len(list_of_sets)))

你会看到打印:

0 1
{2, 3} 2  # < we've got a problem here
...
TypeError: list indices must be integers or slices, not set

你的意思是减少 list_of_sets 本身:

def intersection_of_sets(list_of_sets):
    return reduce(lambda x, y: x & y, list_of_sets)

演示:

In [1]: from functools import reduce

In [2]: def intersection_of_sets(list_of_sets):
   ...:     return reduce(lambda x, y: x & y, list_of_sets)
   ...: 

In [3]: print(intersection_of_sets([{1, 2, 3}, {2, 3, 4}, {2, 5}, {1, 2, 5}]))
set([2])

因为你访问的是一整套,比如{1,2,3}。 请尝试:

set([2][1])

迭代所有这些都有效:

def intersection_of_sets(list_of_sets):
    res = list_of_sets[0]
    for s in list_of_sets[1:]:
        res &= s
    return res

print(intersection_of_sets([{1, 2, 3}, {2, 3, 4}, {2, 5}, {1, 2, 5}]))

输出:

{2}

这里的&=是就地运算符,意思和res = res & s一样。

集合有内置函数,intersection

a = {1, 2, 3}
b = {1, 2, 4}
c = {0, 2, 5}
a.intersection(b).intersection(c)

returns: {2}

只需创建一个递归函数来比较前两个并将结果推送到数组或结果集中只有一个长度。

def compareSets(arr):
    if len(arr) == 1: return arr[0]
    intersect = arr[0].intersection(arr[1])
    if len(arr) == 0: return {}
    arr.append(intersect)
    return compareSets(arr)