2012-01-26 3 views
2
I 첫번째 숫자가 아닌 요소로부터리스트의 모든 요소를 ​​추출 할

모든 요소 : I 원하는추출 첫번째 숫자가 아닌 요소

input = [u'12', u'23', u'hello', u'15', u'guys'] 

:

output = [u'hello', u'15', u'guys'] 

비를 파이썬 버전은 다음과 같습니다 :

input_list = [u'12', u'23', u'hello', u'15', u'guys'] 

non_numeric_found=False 
res = [] 
for e in input_list: 
    if not non_numeric_found and e.isnumeric(): 
     continue 
    non_numeric_found=True 
    res.append(e) 

더 나은 구현을위한 제안 사항은 무엇입니까?

답변

6

당신은 itertools.dropwhile를 사용할 수 있습니다

약간 이상하지만 더 명시 적 버전
import itertools 
input_list = [u'12', u'23', u'hello', u'15', u'guys'] 
res = list(itertools.dropwhile(lambda s: s.isdigit(), input_list)) 
+0

한 단지로 변경 :'목록 (itertools. dropby (str.isdigit, input_list))' – eumiro

+0

+1 @eumiro, 유니 코드이어야합니다 .isdigit –

+0

@eumiro 그 변화는 코드 늑대 밖에서는 좋지 않을 것입니다. str이 아닌 입력을 허용하지 않으며, 가장 중요한 것은's'가'str'이 아니라'unicode '이기 때문에이 경우 실패합니다. – phihag

1

itertools없이 다음 itertools에 대한

it = iter(input_list) 
res = [] # in case the list has no non-numeric elements 

for e in it: 
    if not e.isnumeric(): 
     res = [e] + list(it) 
     break 
+1

@phihag : 참. 답변을 업데이트했습니다. –

1
def f(ls): 
if (len(ls) == 0 or not ls[0].isnumeric()): 
    return ls 
return f(ls[1:]) 

input = [u'12', u'23', u'hello', u'15', u'guys'] 
f(input) 
>>> [u'hello', u'15', u'guys']