2013-12-19 38 views
0

我有我正在使用的这段代码。我是一个新手,所以请原谅我的无知。For循环与如果不按预期方式工作

预期的逻辑是:

在列表Y A值,发现在表S任何匹配并打印出表S(未列出y)处的值。 我目前的代码打印列表y,但我实际上想要列表s。

这里是我当前的代码:

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

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

我打算打印“樵夫”和“香蕉船”,但该代码是打印“A” 请帮助:)

谢谢

+0

也许只是一个'如果中的Y:打印s' –

+0

您的与'任何'似的过于复杂。这种逻辑在python中通常非常简单直接。 – keyser

+0

当描述与代码非常不同时,很难猜出您需要什么。你写的是“列表”,但代码中没有任何内容。 –

回答

1

打印“一”是正确的,如果你想打印“樵夫”,附加到字母列表中的那些字符(即变量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 
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的子串( '伐木工'),它也打破后,你打印,所以你不可能打印多次。

+0

根据问题'y'将会成为一个列表,因此可能需要一些循环/列表理解 – keyser

+0

真棒。谢谢。如果我在列表中有多个元素,该怎么办?例如y ='a','m','j'和s ='伐木工','香蕉分割'非常感谢你。 – BlackHat

+0

很酷:)我已经编辑了我在y中的多个字符的代码。 – Ffisegydd

相关问题