python for循环使额外的列表

时间:2014-07-29 04:59:27

标签: python for-loop

我有一个列表,如果我在与列表匹配的文本文件中找到一个单词,那么它必须打印“是”'否则打印' no'。如果我增加列表,那么它会产生一个大的列表。

编码:

keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        for key in keywords:
            if key in line:
               a = 'yes'
            else:
                a = 'no'
            print a

我有一个文本文件qwe.txt:

i havea bike good
condition
yes
I have a car
Skoda Superb
yes good

它的产生:

yes
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
yes
no
no

取代Desired:

yes
no
no
no
no
no
yes

请帮助我减少额外的' no'!

4 个答案:

答案 0 :(得分:3)

不打印'不'直到你通过关键字列表完成它:

keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        a = 'no'  # Start by assuming it's not there
        for key in keywords:
            if key in line:
               a = 'yes'
               break  # Now that we've found a match, we can stop looking
        print a

另请注意,您可以使用生成器表达式和any内置函数简化代码:

keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        a = 'yes' if any(key in line for key in keywords) else 'no'
        print a

答案 1 :(得分:1)

检查组中的成员资格是set擅长的:

keywords=set(['good','lorry','truck'])
with open('qwe.txt','r') as file:
    for line in file:
        if keywords.intersection(line.split()):
            print 'yes'
        else:
            print 'no'

答案 2 :(得分:0)

试试这个

keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        for key in keywords:
            if key in line:
               a = 'yes'
               break
            else:
                a = 'no'
        print a

答案 3 :(得分:0)

试试这个:

keywords=['good','lorry','truck']
with open('qwe.txt','r') as file:
    for line in file:
        found_match="no"
        for key in keywords:
            if key in line:
                found_match="yes"
        print found_match

要小心你的缩进。对于每个"行",每个"键"都有一个print语句。使用3个键和6个键(如果底部有一个空行,可能是7个),你会得到3 * 6 = 18个响应。