<p>在映射字符串之前,将字符串拆分为一个列表。<strong>map()</strong>用于列表、集合和dict,<em>不是</em>字符串。在</p>
<pre><code>word_list = words_str.split(" ")
</code></pre>
<p>避免使用<em>map filter reduce</em>,除非您的赋值指定它;<a href="http://www.python.org/~guido/" rel="nofollow">GVR</a><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196" rel="nofollow">says so</a>。正确的解决方案使用Python的<a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>语法。事实上,你可以用一个非常讨厌的单句话:</p>
^{pr2}$
<p>分解它。。。在</p>
<ol>
<li>在dictionary对象中捕获它以便稍后打印:<code>pal_count = {</code></li>
<li>定义返回对象:<code>x: word_list.count(x)</code>我们使用键:值语法将回文(<em>x</em>)与其出现的次数相关联。<strong><a href="http://docs.python.org/library/stdtypes.html#str.count" rel="nofollow">count()</a></strong>类似于列表的内置reduce函数。在</li>
<li>用一个<strong>for循环</strong>遍历我们的列表,将当前值赋给'x':<code>for x in word_list</code></li>
<li>我们只想返回回文,所以我们添加了一个比较运算符到<em>filter</em>out坏值:<code>if x == x[::-1] # cool logic, btw</code></li>
<li>万岁!<code>}</code></li>
</ol>
<p>顺便说一下,我只是做你的作业,因为我从来没有做过我的作业。在</p>
<p>更慢、更不灵活、更不可移植、更少的<em>awesome</em>等效使用嵌套for循环:</p>
<pre><code>pal_count = dict()
for x in word_list: # same loop
if x == x[::-1] # is this a palindrome?
if x in pal_count: # have we seen before?
pal_count[x] += 1
else: # this one is new!
pal_count.setdefault(x, 1)
</code></pre>