2013-12-19 81 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

相關問題