簡體   English   中英

如何將循環轉換為最短列表理解形式?

[英]How to convert loop to shortest list comprehension form?

我試圖獲得最短的代碼來獲取唯一參數列表(按出現順序)。 這些參數在每個parameter = something的左邊。 我能夠構建以下有效的循環並將參數存儲在h

data = [
    'B = 3', 
    'T = 0', 
    'N = 5', 
    'V = 2', 
    'N = 1', 
    'V = 4',
    'B = 7', 
    'T = 2',
]

h = []
for d in data:
    el = d.split("=", 1)[0].strip()
    if el not in h:
        h.append(el)

>>> h
['B', 'T', 'N', 'V']

然后,我想在列表理解中轉換它並且它有效但我認為有一種方法可以將它寫得更短而無需重復d.split("=", 1)[0].strip()兩次.

h = []
[h.append(d.split("=", 1)[0].strip()) for d in data if d.split("=", 1)[0].strip() not in h ]

我試過這個但似乎不是正確的語法。

h = []
[el = d.split("=", 1)[0].strip() h.append(el) for d in data if el not in h ]

嘗試:

h = list(set(s.split()[0].strip() for s in data))
print(h)

印刷:

['N', 'V', 'B', 'T']

在保留順序的同時(假設你真的只想要第一個字符):

list(dict.fromkeys(s[0] for s in data))

或者獲取空格前的第一組字符:

list(dict.fromkeys([s.split()[0] for s in data]))

您也可以使用 map 和operator.itemgetter來了解這個

from operator import itemgetter

list(dict.fromkeys(map(itemgetter(0), map(split, data))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM