简体   繁体   English

列表理解:包含但不包含(Python)

[英]List Comprehension: Contains This and not That (Python)

I'm reading a file line by line, and I've separated it out with line.split(',') the way I want to. 我正在逐行读取文件,并使用line.split(',')将其分隔开。 Now I want to flag, copy to list, or perform a function on: 现在,我要标记,复制到列表或执行以下功能:

A line which contains the string 'THIS', but not 'THAT'. 包含字符串“ THIS”但不包含“ THAT”的行。

I'm shooting for something that looks like this: 我正在拍摄看起来像这样的东西:

if any(('THIS' in s for s in csvLine) if any('THAT' **!in** s for s in csvLine):
        print csvLine

but this isn't good syntax at all. 但这根本不是一个好的语法。 I think I'm in over my head using list comprehension, but I have successfully done it before thanks to this answer . 我想我会使用列表理解来解决问题,但是由于有了这个答案 ,我已经成功地做到了。

I do have a working solution with the code below, but I sense there's something better: 我的下面的代码确实有一个可行的解决方案,但我觉得还有更好的方法:

    if any('THAT' in s for s in csvLine):
        print "do nothing"
    elif any('THIS' in s for s in csvLine):
        print "do something"
    else:
        print "do nothing"

How do I compress the logic of these if-else statements into more beautiful, pythonic, code? 如何将这些if-else语句的逻辑压缩为更漂亮的pythonic代码?

This is my actual, not-generalized, plain English question: if a line contains CHAT and TRANSFER, then it is unimportant. 这是我的实际的,不是一般的,简单的英语问题:如果一行包含CHAT和TRANSFER,则它并不重要。 If it contains only CHAT, it is unimportant. 如果仅包含CHAT,则不重要。 If it contains just TRANSFER and not the word CHAT, it is noteworthy and I want to do something with the line. 如果它仅包含TRANSFER而不包含CHAT单词,则值得注意,我想对该行进行处理。 How to I find the lines with the word TRANSFER, but not CHAT in them? 我如何找到带有单词TRANSFER的行,但在其中找不到CHAT?

Not sure if I fully understand - why do you need to iterate through the line? 不知道我是否完全理解-为什么您需要遍历整个行? This seems like it would work better: 这似乎会更好:

if 'this' in csvLine and not 'that' in csvLine:
    do_something()
if any('THIS' in s for s in csvLine) and all('THAT' not in s for s in csvLine):

is the same as 是相同的

if any('THIS' in s for s in csvLine) and not any('THAT' in s for s in csvLine):

The 'THIS' part will stop iterating as soon as 'THIS' is found and the 'THAT' will stop iterating as soon as 'THAT' is found. 一旦找到“ THIS”,“ THIS”部分将停止迭代,而一旦找到“ THAT”,则“ THAT”将停止迭代。 It is possible, that one or both of the iterations will have to complete. 可能有一个或两个迭代都必须完成。

From the question you linked to, make a slight modification: 从您链接到的问题进行一些修改:

csv_line = ["Has CHAT", "Has TRANSFER", "Has CHAT and TRANSFER"]
transfers = [s for s in csv_line if "TRANSFER" in s and "CHAT" not in s]
print transfers

>>> ['Has TRANSFER']

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

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