簡體   English   中英

列表理解中的多個if

[英]Multiple ifs within list comprehension

考慮到某些項目(如果存在於item['keys']則不會包含在itemDict我使用了列表itemDict ,該方法應該將keysvalues存儲在itemDict變量中。 我已經使用了多個if條件來實現這一點。

這是我嘗試過的:

itemDict = {item['keys']:item['value'] for item in soup.select('input[keys]') if '$cmdPrint' not in item['name'] and 'btnView' not in item['name'] and 'btnMyDoc' not in item['key']}

我如何重寫這些條件以使其簡潔?

您可以使用check功能並使用all內置功能。 還重新設置對可讀性的理解。

def check(item):
    return all(('$cmdPrint' not in item['name'],
           'btnView' not in item['name'],
           'btnMyDoc' not in item['key']))

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if check(item)}

或在理解中使用它,但這是一個漫長的理解。

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if all(('$cmdPrint' not in item['name'],
                    'btnView' not in item['name'],
                    'btnMyDoc' not in item['key']))}

或者只是使用常規的for循環:

itemDict = {}
for item in soup.select('input[keys]')
    if check(item):
        itemDict[item['keys']] = item['value']

暫無
暫無

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

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