2016-06-23 5 views
1

for 루프를 사용하여 input_string을 아래 주석으로 변환해야합니다. 먼저 split() 함수를 사용하여 슬라이스했지만 이제는 입력 문자열을 ['result1', 'result2', 'result3', 'result5']으로 바꾸어야합니다. 나는 .xls과 대시 ('')를 대체하려고했지만 문자열 출력은 변경되지 않았습니다. 제발 아무것도 가져 오지 마세요, 나는 함수와 루프에서만 이것을하려고합니다. 목록에서 여러 부분 문자열을 바꾸는 방법은 무엇입니까?

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls" 
# Must be turned into ['result1','result2', 'result3', 'result5'] 

splitted = input_string.split(',') 

for c in ['.xls', '-', '0']: 
    if c in splitted: 
     splitted = splitted.replace(splitted, 'c', '') 

내가 splitted 입력

는, 출력은 ['01-result.xls', '2-result.xls', '03-result.xls', '05-result.xls'] 따라서 아무 것도 발생하지 않습니다이다.

+0

이 경우에는 일반적으로 사용하지 않는 것이 일반적입니다. – marjak

+1

정규 표현식을 사용할 수 있습니다. –

+0

@BenjaGarrido 예, 이해하기 쉽지만 유감스럽게도 느립니다. –

답변

3

re module's sub 함수와 split을 사용하십시오.

>>> input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls" 
>>> import re 
>>> re.sub(r'(\d+)-(\w+)\.xls',r'\2\1',input_string) 
'result01,result2,result03,result05' 
>>> re.sub(r'(\d+)-(\w+)\.xls',r'\2\1',input_string).split(',') 
['result01', 'result2', 'result03', 'result05'] 

더 수입을 사용하지, 당신은 ,에 그것을 분할 후 문자열을 통해 여기, 우리 루프를 list comprehension

>>> [''.join(x.split('.')[0].split('-')[::-1]) for x in input_string.split(',')] 
['result01', 'result2', 'result03', 'result05'] 

너 한테을 사용할 수 있습니다. 이제 우리는 .에있는 개별 단어를 나눠서 -에 첫 번째 요소를 나눕니다.

이 목록의 이해가 무엇인지 이해하기, 읽기 What does "list comprehension" mean? How does it work and how can I use it?

받는오고 - 우리는 지금 우리가 쉽게 join.


목록 빌려 응답의

완전한 설명 할 수와 단어를 가지고 대답

,에 입력 목록을 분할은 우리에게 개별 파일 이름의 목록을 제공

우리가 파일 이름 만이 아닌 확장을 필요로 691,363,210
>>> input_string.split(',') 
['01-result.xls', '2-result.xls', '03-result.xls', '05-result.xls'] 

이제 지능형리스트 구조를 사용하여, 우리는이를 통해

>>> [i for i in input_string.split(',')] 
['01-result.xls', '2-result.xls', '03-result.xls', '05-result.xls'] 

을 반복 할 수있는, 우리 split.를 사용하여 첫 번째 값을하여.

>>> [i.split('.')[0] for i in input_string.split(',')] 
['01-result', '2-result', '03-result', '05-result'] 

다시 말하면 번호와 이름이 두 부분으로 필요합니다. 그래서 우리는 다시 우리가 "namenumber"입니다 필요하지만 형식, 이제 우리는 목록에서 [번호, 이름을]이 -

>>> [i.split('.')[0].split('-') for i in input_string.split(',')] 
[['01', 'result'], ['2', 'result'], ['03', 'result'], ['05', 'result']] 

로 분할합니다. 따라서 우리는 두 가지 옵션

i.split('.')[0].split('-')[1]+i.split('.')[0].split('-')[0]처럼 CONCAT
  • 있습니다. 이것은 불필요하게 긴 방법입니다.
  • 이를 반대로 결합하십시오. 슬라이스를 사용하여리스트 (How can I reverse a list in python? 참조)와 str.join을 뒤섞어 ''.join(x.split('.')[0].split('-')[::-1])처럼 결합 할 수 있습니다.

그래서 우리는

>>> [''.join(x.split('.')[0].split('-')[::-1]) for x in input_string.split(',')] 
['result01', 'result2', 'result03', 'result05'] 
+1

haha ​​내 답변을 제출하기 전에 귀하의 목록을 보지 못했습니다. +1 두 솔루션. – Jeremy

+0

@Jeremy 감사합니다. 귀하의 답변을 보았다면 편집하지 않았을 것입니다. :) –

+0

누군가 Rao의 목록 이해력 해답에서 일어나는 일을 정확하게 설명 할 수 있습니다. 그는 '-'과 '.'로 나뉘어 합류했다. ? – marjak

2

는 여기에 다시를 사용하지 않으려면 목록의 이해와 문자열 조작을 사용하여 솔루션입니다 우리의 최종 목록의 이해를 얻을. 이 목록의 이해 작동

input_string = "01-result.xls,2-result.xls,03-result.xls,05-result.xls" 
# Must be turned into ['result1','result2', 'result3', 'result5'] 

splitted = input_string.split(',') 

#Remove extension, then split by hyphen, switch the two values, 
#and combine them into the result string 
print ["".join(i.split(".")[0].split("-")[::-1]) for i in splitted] 

#Output 
#['result01', 'result2', 'result03', 'result05'] 

방법은 다음과 같습니다

  1. 결과의 목록을 타고 ".XLS"를 제거합니다. i.split(".)[0]
  2. -에서 분할하고 숫자와 "결과"의 위치를 ​​전환하십시오. .split("-")[::-1]
  3. 목록의 모든 항목에 대해 목록에 문자열을 가입시킵니다. "".join()
+0

Pro-tip, 항상 코드 블록 외부에서 설명하십시오. 코멘트를위한 CSS는 눈을 맞추기에는 너무 희미합니다. –

관련 문제