Question

say a list of tuples like this:

y=[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]

I am trying to use reduce() feature to make a string of each element in y. ''.join(list(x) gives lets say 'abc' for 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'
Was it helpful?

Solution 2

reduce() is called with 2 arguments always, so your u argument is set to the second value in y, a tuple. The default is ignored.

You really shouldn't use reduce() here. reduce() you need when you want to use the next element in the iterator for each loop iteration to calculate one aggregate value.

You are mapping instead:

map(''.join, y)

or use a list comprehension:

[''.join(x) for x in y]

OTHER TIPS

Not clear why reduce in involved. Are you looking for:

[''.join(t) for t in y]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top