添加“?”到lis中每个字符串的结尾

2024-10-03 06:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加个问号(?)到列表中每个字符串的末尾。你知道吗

目前,它正在打印['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']))

谢谢你!你知道吗


Tags: ofthe字符串列表deflistcatreturns
3条回答

使用此选项:

def suffixQuestionMark(str_list):
    return map(lambda el: el + '?', str_list)

输出:

['cat?', 'dog?', 'person?']

你的代码是这样的:

str_list = map(lambda x: s + '?', str_list)

这行执行3次(因为迭代列表中有3个单词),用['word?', 'word?', 'word?']列表覆盖每个迭代结束时的str_list,其中word在第一次迭代中是cat,在第二次迭代中是dog,最后是person。你知道吗

这就是为什么你会得到['person?', 'person?', 'person?']列表。你知道吗

请注意,实际上没有来使用map函数,列表理解在这里很好:

def suffix_question_mark(words):
    return [word+'?' for word in words]

返回列表comp是最简单的解决方案:

return [s + "?" for s in l]

它也将比使用地图更有效。你知道吗

你自己的代码有很多潜在的问题,为什么你会看到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>的内容没有返回字符串列表。你知道吗

相关问题 更多 >