new_list = ['\n{}'.format(i) if 'Wednesday' in i else i for i in list_]
示例:
In [92]: l = ['the dog ran', 'tomorrow is Wednesday', 'hello sir']
In [93]: ['\n{}'.format(i) if 'Wednesday' in i else i for i in l]
Out[93]: ['the dog ran', '\ntomorrow is Wednesday', 'hello sir']
处理列表中的项目以生成新列表需要列表理解。将它与
x if y else z
条件表达式结合起来,可以根据需要修改项。你知道吗列出理解和条件表达式:
示例:
顺便说一下,将变量设置为
list
是个坏主意,因为它会隐藏内置的list
类型。你知道吗您可以在列表理解中使用
endswith
:输出:
相关问题 更多 >
编程相关推荐