我想加个问号(?)到列表中每个字符串的末尾。你知道吗
目前,它正在打印['person?', 'person?', 'person?']
,但我希望它打印['cat?', 'dog?', 'person?']
。你知道吗
有人能帮我找出我做错了什么吗?你知道吗
def suffixQuestionMark(str_list):
'''Returns a list of the same strings but with ? suffixed to each'''
for s in str_list:
str_list = map(lambda x: s + '?', str_list)
return str_list
print (suffixQuestionMark(['cat', 'dog', 'person']))
谢谢你!你知道吗
使用此选项:
输出:
你的代码是这样的:
这行执行3次(因为迭代列表中有3个单词),用
['word?', 'word?', 'word?']
列表覆盖每个迭代结束时的str_list
,其中word
在第一次迭代中是cat
,在第二次迭代中是dog
,最后是person
。你知道吗这就是为什么你会得到
['person?', 'person?', 'person?']
列表。你知道吗请注意,实际上没有来使用
map
函数,列表理解在这里很好:返回列表comp是最简单的解决方案:
它也将比使用地图更有效。你知道吗
你自己的代码有很多潜在的问题,为什么你会看到
person?
三次是因为你在lambda中使用了s
,所以在最后一次迭代中,当s
是person时,你把所有的值映射成等于person + ?
。即使在循环中更改为map(lambda x: x + '?', str_list)
,也会将* len(l)
?
添加到每个字符串中。您只需要return map(lambda x: x + '?', str_list)
,但是在这个实例中使用map没有任何好处。你知道吗您也没有像标签所暗示的那样使用python3,如果您是这样的话,您会看到类似
<map object at 0x7fd27a4060f0>
的内容没有返回字符串列表。你知道吗相关问题 更多 >
编程相关推荐