0

说出这样的元组列表:

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

我正在尝试使用 reduce() 功能来制作 y 中每个元素的字符串。''.join(list(x) 让我们说'abc'进行第一次迭代。

z=reduce(lambda x, u=dict(): u.setdefault(''.join(list(x)), []).extend(''.join(list(x))), y)

错误:

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'
4

2 回答 2

2

不清楚为什么要减少参与。您是否在寻找:

[''.join(t) for t in y]
于 2013-05-19T14:29:47.643 回答
1

reduce()始终使用 2 个参数调用,因此您的u参数设置为y元组中的第二个值。默认值被忽略。

你真的不应该reduce()在这里使用。reduce()当您想为每个循环迭代使用迭代器中的下一个元素来计算一个聚合值时,您需要。

您正在映射

map(''.join, y)

或使用列表理解:

[''.join(x) for x in y]
于 2013-05-19T14:23:04.860 回答