목록에서 두 가지 유형의 요소를 병합하는 해결책을 찾기가 힘듭니다.python으로 목록의 요소를 조건과 병합하는 방법은 무엇입니까?
list_i = ['teacher', '10', 'student', '100', 'principle', '2']
결과 :
list_1 = ['teacher:10', 'student:100', 'principle:2']
이 어떤 도움을 주시면 더 좋구요!
목록에서 두 가지 유형의 요소를 병합하는 해결책을 찾기가 힘듭니다.python으로 목록의 요소를 조건과 병합하는 방법은 무엇입니까?
list_i = ['teacher', '10', 'student', '100', 'principle', '2']
결과 :
list_1 = ['teacher:10', 'student:100', 'principle:2']
이 어떤 도움을 주시면 더 좋구요!
가 사용 다음 코드는
[':'.join(item) for item in zip(list_i[::2],list_i[1::2])]
이 두 부품의 목록을 슬라이스 단지 것 및 우편
그들을 조인 이[list_i[i] + ":" + list_i[i+1] for i in range(0, len(list_i), 2)]
이 생산
고마워, 나는 그것을 밖으로 시도. 그것은 작동합니다. – dlfjj
import more_itertools as mit
iterable = ['teacher', '10', 'student', '100', 'principle', '2']
[":".join(i) for i in mit.windowed(iterable, 2, step=2)]
# ['teacher:10', 'student:100', 'principle:2']
는 다른 방법으로도 more_itertools
에서 구현되는 grouper
itertools recipe 적용
> pip install more_itertools
코드 : more_itertools
, 타사 라이브러리를 사용하여, 당신은 sliding window 기술을 적용 할 수 있습니다.
[":".join(i) for i in mit.grouper(2, iterable)]
# ['teacher:10', 'student:100', 'principle:2']
정확히 붙어 있습니까? 2로 반복? 문자열로 작업? –