認為
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 函式解決這個問題,盡管我目前正在學習基本的東西。
uj5u.com熱心網友回復:
thread_sold_split_bad = [
[x for x in y.split("&")] if "&" in y else y for y in thread_sold
]
您上面的嘗試不起作用,因為您正在執行嵌套串列推導而不是普通推導(注意主括號內的括號)。這是更正后的版本:
>>> thread_sold_split = [x for y in thread_sold for x in y.split("&")]
>>> print(thread_sold_split)
['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow']
uj5u.com熱心網友回復:
你可以使用functools.reduce:
from functools import reduce
reduce(lambda x, y: x y, [x.split("&") for x in thread_sold])
或者
import itertools
list(itertools.chain.from_iterable(x.split("&") for x in thread_sold))
輸出
['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394056.html
上一篇:Forrester首份《低代碼平臺中國市場現狀分析報告》哪些廠商入圍了
下一篇:STM32+W5500網路通信
