2013-12-19 6 views
0

나는이 작은 코드 조각을 가지고 있습니다. 나는 초심자이므로 친절하게도 내 무지를 사면한다.for 루프 함께 예상대로 작동하지 않는 경우

의도 논리는 다음과 같습니다 목록 Y의 값에 대한

는 목록의 어떤 경기를 찾아 목록들 (Y를 나열하지)의 값을 출력. 현재 코드가 y리스트를 출력하지만 실제로 목록을 원합니다. I '는' :

당신에게

감사 도와주세요 인쇄있는 그대로 '나무꾼'과 '바나나 분할'하지만 코드를 인쇄하려는

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

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

: 여기

내 현재 코드입니다
+0

을 할 수있는 것 같아요 아마도 단지'의에서 Y는 경우 : –

+0

당신을위한 s' 인쇄 'any '를 가진 루프는 지나치게 복잡해 보입니다. 이런 종류의 논리는 종종 파이썬에서 매우 간단하고 직관적입니다. – keyser

+0

설명이 코드와 너무 다를 때 필요한 것을 추측하기가 어렵습니다. 당신은 "목록"에 관해 글을 쓸 수는 있지만 코드에는 아무 것도 없습니다. –

답변

1

인쇄 "는"올바른

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' 

다음 편집 당신이 (당신의 의견은 제안) 문자의 목록이있는 경우 : 예에서 문자열 ('A') s의 문자열인지 여부를

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) 

이 확인 ('lumberjack'), 인쇄 한 후에도 깨져서 여러 번 인쇄하지 못할 수도 있습니다. 네가 원하는 인쇄 "나무꾼은"알파 목록에 해당 문자 (즉, 변수 y)를 추가하면

+0

질문에 따르면 'y'는 목록이되므로 일부 루프/목록 이해가 필요할 수 있습니다. – keyser

+0

굉장해. 고맙습니다. 목록에 여러 요소가있는 경우 어떻게됩니까? 예를 들어, y = 'a', 'm', 'j'및 s = 'lumberjack', 'banana split' – BlackHat

+0

Cool :) y에서 여러 문자로 코드를 편집했습니다. – Ffisegydd

관련 문제