Python: AttributeError: 'tuple' object has no attribute 'setdefault' -
say list of tuples this:
y=[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
i trying use reduce() feature make string of each element in y. ''.join(list(x) gives lets 'abc' first iteration.
z=reduce(lambda x, u=dict(): u.setdefault(''.join(list(x)), []).extend(''.join(list(x))), y)
error:
attributeerror traceback (most recent call last) <ipython-input-102-79858e678e78> in <module>() ----> 1 z=reduce(lambda x, u=dict(): u.setdefault(''.join(list(x)), []).extend(''.join(list(x))), y) <ipython-input-102-79858e678e78> in <lambda>(x, u) ----> 1 z=reduce(lambda x, u=dict(): u.setdefault(''.join(list(x)), []).extend(''.join(list(x))), y) attributeerror: 'tuple' object has no attribute 'setdefault'
reduce()
called 2 arguments always, u
argument set second value in y
, tuple. default ignored.
you shouldn't use reduce()
here. reduce()
need when want use next element in iterator each loop iteration calculate 1 aggregate value.
you mapping instead:
map(''.join, y)
or use list comprehension:
[''.join(x) x in y]
Comments
Post a Comment