【发布时间】:2022-01-25 04:25:15
【问题描述】:
假设
thread_sold = ['white', 'white&blue', 'white&blue', 'white', 'white&yellow', 'purple', 'purple&yellow', 'purple&yellow']
我需要该列表中的所有项目,有时用 & 分隔,有时不用。下面的函数有效,但我想知道如何通过列表理解来做到这一点。
def cant_list_comprehend(lst):
thread_sold_split = []
for i in lst:
if "&" in i:
for x in i.split("&"):
thread_sold_split.append(x)
else:
thread_sold_split.append(i)
return thread_sold_split
returns ['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow', 'blue', 'blue', 'purple', 'blue', 'white', 'white'...]
我试过的列表理解:
thread_sold_split_bad = [
[x for x in y.split("&")] if "&" in y else y for y in thread_sold
]
returns ['white', ['white', 'blue'], ['white', 'blue'], 'white', ['white', 'yellow'], 'purple', ['purple', 'yellow'],...]
如果可以避免的话,我想避免在我的代码中添加命名函数,我也有兴趣使用 lambda 函数来解决这个问题,尽管我目前正在学习基本的东西。
【问题讨论】:
-
“我也有兴趣用 lambda 函数解决这个问题”是吧?为什么?
标签: python list lambda list-comprehension