For循环使用If不按预期工作

时间:2013-12-19 17:34:55

标签: python if-statement for-loop

我正在使用这段代码。我是一个新手,请原谅我的无知。

预期的逻辑是:

对于列表y中的值,找到列表s中的任何匹配项并打印出列表s中的值(不是列表y)。 我当前的代码打印出列表y但我实际上想要列表。

这是我目前的代码:

y = ['a','m','j']
s = ['lumberjack', 'banana split']

for x in s:
    if any(x in alpha for alpha in y):
           print x

我打算打印'伐木工人'和'香蕉拆分',但代码打印'a' 请帮助:)

谢谢

2 个答案:

答案 0 :(得分:1)

在你的for循环中,你只是打印当时正在迭代的字符,而不是完整的字符串。

y = 'a'
s = 'lumberjack'

for x in s:
    if any(x in alpha for alpha in y):
       print s # Return 'lumberjack'

编辑如果您有一个字符列表(如您的评论所示),那么:

y = ['a', 'z', 'b']
s = 'lumberjack'

def check_chars(s, chars):
    for char in y:
        if char in s:
            print s
            break

for s in ['lumberjack','banana split']:
    check_chars(s,y)

这会检查y('a')中的字符串是否是s('lumberjack')的子字符串,它在打印后也会中断,因此您不可能多次打印。

答案 1 :(得分:1)

打印“a”是正确的,如果您想要打印“伐木工人”,请将这些字符附加到您的字母列表中(即变量y)

y = 'albumjcker' # all characters inside "lumberjack"
s = 'lumberjack'

for x in s:
    if any(x in alpha for alpha in y):
           print x

应该做的伎俩


尝试:

y = ["a", "b", "c", "l"]
s = ["banana split", "lumberjack"]
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

The animal farm on the left
I had potatoes for lunch

修改

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]
s = list(set(s)) # But NOTE THAT this might change the order of your original list
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

如果订单很重要,那么我猜你只能这样做

y = ["animal","zoo","potato"] 
s =  ["The animal farm on the left","I had potatoes for lunch"]

new = []
for x in s:
    if x not in new:
        new.append(x)
s = new

for words in s:
    for char in y:
        if char in words:
            print (words)
            break