简体   繁体   English

列表理解中的格式打印问题

[英]Format printing issue in list comprehension

Hi all im trying to use list comprehension and some filtering to clean up a list. 大家好,我试图使用列表理解和一些过滤来清理列表。 For some reason (that alludes me) The filtering wont work as expected, ive double checked my syntax and triple checked it im almost positive its correct. 由于某种原因(这暗示了我),筛选将无法按预期工作,我已经仔细检查了我的语法,并且三遍检查了我的语法,几乎肯定了它的正确性。

Im expecting an output similar to this: 我期望输出类似于以下内容:

DOMAINNAME\\USERNAME

What im getting is this 我得到的是什么

C:\python27\filename
DOMAINNAME\USERNAME

The above suggests to me that the .format type formatting is not working in my below code. 上面对我来说,.format类型格式在我的以下代码中不起作用。

def tllocal(domain):
    try:
        out = subprocess.check_output(["tasklist", "/V", "/FO", "List", "/FI", "USERNAME eq {0}\*" .format(domain)])
        users = [item for item in out.split() if "{0}" and "\\" in item .format(domain)]
        sortedl = set(users)
        print sortedl
        for name in sortedl:   
           print name
    except CalledProcessError as e:
        print(e.returncode)
    return sortedl

I believe it is this line causing the problem. 我相信这是导致问题的那条线。

users = [item for item in out.split() if "{0}" and "\\\\" in item .format(domain)]

Any help would be appreciated. 任何帮助,将不胜感激。

You are correct, that is incorrect. 您是正确的,那是不正确的。 This expression 这个表达

if "{0}" and "\\" in item .format(domain)

is parsed as: 解析为:

(if '{0}') and ("\\" in item .format(domain))

Which is always True since the string literal '{0}' is always true. 这始终是True ,因为字符串文字'{0}'总是正确的。

The correct way of writing the above is all : 写上面的正确的方法是all

[item for item in out.split() if all(x in item for x in (domain, '\\'))]

Or simply and , since you only have two elements: 或简单地使用and ,因为您只有两个元素:

[item for item in out.split() if domain in item and '\\' in item]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM