파이썬 2에서 map() 함수는 리스트를 반환하지만, 파이썬 3에서는 <map object at 0x\*\*\*\*\*\*\*\*> 객체를 반환합니다.
map() 함수는 제공된 함수를 지정된 시퀀스에 적용하여 매핑합니다.
첫 번째 매개변수인 function은 시퀀스의 각 요소에 대해 함수를 호출하고, 각 function 함수의 반환값을 포함하는 새로운 리스트를 생성합니다. 이는 function을 iterable의 각 항목에 적용하고 그 결과를 출력하는 반복자를 반환합니다. 추가적인 iterable 매개변수가 전달되면, function은 동일한 개수의 인수를 받아야 하며 모든 iterable 객체에서 병렬로 가져온 항목에 적용됩니다. 여러 개의 iterable이 있는 경우, 가장 짧은 iterable이 소진되면 전체 반복이 종료됩니다.
문법
map() 함수 문법:
map(function, iterable, ...)
매개변수
- function -- 함수
- iterable -- 하나 이상의 시퀀스
print(map(str, [1, 2, 3, 4]))
list(map(str, [1, 2, 3, 4])) # 외부 list가 없으면 <map object at 0x\*\*\*\*\*\*\*\*> 반환
결과:
['1', '2', '3', '4']
파이썬의 join()과 os.path.join() 함수
join(): 문자열 배열을 연결합니다. 문자열, 튜플, 리스트의 요소를 지정된 구분자로 연결하여 새로운 문자열을 생성합니다.
os.path.join(): 여러 경로를 조합하여 반환합니다.
class DataConverter:
def __init__(self):
pass
def convert_types(self):
text = 'python12345'
print('text:', text, type(text))
# 문자열을 리스트로 변환
char_list = list(text)
print('char_list:', char_list, type(char_list))
# 문자열을 튜플로 변환
char_tuple = tuple(text)
print('char_tuple:', char_tuple, type(char_tuple))
# 문자열을 리스트/튜플로 변환은 직접 가능
# 리스트/튜플을 문자열로 변환하려면 join() 함수 사용
# 리스트를 문자열로 변환
joined_str = ''.join(char_list)
print('joined_str:', joined_str, type(joined_str))
# 튜플을 문자열로 변환
joined_str2 = ''.join(char_tuple)
print('joined_str2:', joined_str2, type(joined_str2))
문자열을 리스트/튜플로 변환은 직접 가능합니다. 하지만 리스트/튜플을 문자열로 변환하려면 join() 함수가 필요합니다. join() 함수는 다음과 같이 설명됩니다:
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
join() 함수는 반복 가능한 객체를 인자로 받으며, 요소 간의 구분자가 "S"인 새로운 문자열을 반환합니다. 리스트, 튜플, 문자열을 인자로 받을 수 있습니다.
sample = 'programming'
result = '@'.join(sample)
print(type(result), result)
print("*".join([1,2,3,4]))
print("*".join(map(str,[1,2,3,4])))
다양한 데이터 타입에 join() 적용
리스트에 join() 적용
items = ['apple', 'banana', 'cherry', 'date']
print(' '.join(items)) #apple banana cherry date
print(';'.join(items)) #apple;banana;cherry;date
print('.'.join(items)) #apple.banberry.cherry.date
print('-'.join(items)) #apple-banana-cherry-date
문자열에 join() 적용
text = 'python programming'
print(' '.join(text)) # p y t h o n p r o g r a m m i n g
print('-'.join(text)) # p-y-t-h-o-n- -p-r-o-g-r-a-m-m-i-n-g
print(':'.join(text)) # p:y:t:h:o:n: :p:r:o:g:r:a:m:m:i:n:g
튜플에 join() 적용
fruits = ('apple', 'banana', 'cherry', 'date')
print(' '.join(fruits)) # apple banana cherry date
print('-'.join(fruits)) # apple-banana-cherry-date
print(':'.join(fruits)) # apple:banana:cherry:date
딕셔너리에 join() 적용 (순서 없음)
user_data = {'id1':'user1', 'id2':'user2', 'id3':'user3', 'id4':'user4'}
print(' '.join(user_data)) # id1 id2 id3 id4
print('-'.join(user_data)) # id1-id2-id3-id4
print(':'.join(user_data)) # id1:id2:id3:id4
문자열 분리 후 join()으로 재조합
url = 'website-homepage-about-contact'
print(url.split('-')[1:]) # 첫 번째 이후 요소 ['about', 'contact']
print('-'.join('website-homepage-about-contact'.split('-')[1:])) # 첫 번째 이후 모든 요소를 -로 연결
url1 = 'website-homepage-about'
print('-'.join(url1.split('-')[:-1])) # 마지막 요소 제외하고 연결
print('website-homepage-about'.split('-')[-1]) # 마지막 - 이후 내용 추출
경로 조합에 os.path.join() 사용
import os
print(os.path.join('/project/', 'src/', 'main.py')) #/project/src/main.py