Decrease with empty set as initial value

I have a list of lists, and I want to build a set of elements that are present in all sublists.

example: a = [[1,2],[2,3]] should give set([1,2,3])

I tried decreasing (lambda x, y: x.update (y), a, set ([])), but it raises AttributeError: 'NoneType' object does not have attribute 'update'

Can someone tell me how to do this using the cut function?

+4
source share
6 answers

The problem is that update() in the set returns None , not the set. This is documented and expected behavior. Assuming you want to use update() for some reason, you can write your lambda like this:

  lambda x, y: x.update(y) or x 

The or clause returns x if the first clause is false (which None is).

Indeed, I think you want to use union() instead of update() . This is basically the same and returns the result.

 lambda x, y: x.union(y) 

By the way, you can just write set() to get an empty set, you do not need set([]) . Thus, the rewritten reduce() would be:

 reduce(lambda x, y: x.union(y), a, set()) 

Others have posted additional options, each of which matters, making you think about how they work.

+5
source

According to the request:

 >>> a = [[1,2],[2,3]] >>> reduce(lambda s, elems: s.union(elems), a, set()) set([1, 2, 3]) 

Another way is just for fun:

 >>> from itertools import chain >>> set(chain.from_iterable(a)) set([1, 2, 3]) 

And one more thing to be cool:

 >>> set.union(set(), *a) set([1, 2, 3]) 
+8
source

As already mentioned, how to perform this task with reduce() , I already answered, but I think it is less difficult to do with itertools.chain.from_iterable() :

 import itertools a = [[1, 2], [2, 3]] print set(itertools.chain.from_iterable(a)) 
+1
source

Using

 c =set(); reduce(lambda x,y:c.update(y),a,c) 

Its a set that you use. Since set ([]). Update does not return a value, and the decrease function uses the return from the previous operation. It raises Nonetype, does not have attribute updates.

0
source

The problem with set.update() is that it returns None and itertools .. there should be a better solution. And there is! I think this is cleaner:

 >>> a = [[1,2],[2,3]] >>> reduce(lambda x, y: set(x) | set(y), a) set([1, 2, 3]) 

Note. | makes the union between sets.

0
source

And another with a clean list comprehension:

 >>> a = [[1,2],[2,3]] >>> set([item for sublist in a for item in sublist]) {1, 2, 3} 

what is creating a flat list from a list of lists in Python .

0
source

Source: https://habr.com/ru/post/1383794/


All Articles