[英]Multiple ifs within list comprehension
I've used a list comprehension which is supposed to store keys
and values
in itemDict
variable considering the fact that some items if present in item['keys']
will not be included in itemDict
. 考虑到某些项目(如果存在于item['keys']
则不会包含在itemDict
我使用了列表itemDict
,该方法应该将keys
和values
存储在itemDict
变量中。 I've used multiple if conditions to make that possible. 我已经使用了多个if条件来实现这一点。
This is what I've tried with: 这是我尝试过的:
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']}
How can I rewrite those conditions to make it concise? 我如何重写这些条件以使其简洁?
You could use a check
function and use all
builtin. 您可以使用check
功能并使用all
内置功能。 Also reformat the comprehension for readability. 还重新设置对可读性的理解。
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)}
Or use it in the comprehension, but that's one long comprehension. 或在理解中使用它,但这是一个漫长的理解。
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']))}
Or just use a regular for loop: 或者只是使用常规的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.