Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

목록의 문자열 표현을 Python에서 목록으로 변환

<시간/>

파이썬이 다양한 데이터 유형을 처리함에 따라 목록이 문자열 형태로 나타나는 상황을 접하게 됩니다. 이 기사에서는 문자열을 목록으로 변환하는 방법을 볼 것입니다.

스트립 및 분할 사용

먼저 스트립 방법을 적용하여 대괄호를 제거한 다음 분할 기능을 적용합니다. 쉼표를 매개변수로 사용하는 split 함수는 문자열에서 목록을 생성합니다.

예시

stringA = "[Mon, 2, Tue, 5,]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = stringA.strip('][').split(', ')
# Result and its type
print("final list", res)
print(type(res))

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given string [Mon, 2, Tue, 5,]
final list ['Mon', '2', 'Tue', '5,']

json.loads 사용

json 모듈은 문자열에서 목록으로 직접 변환할 수 있습니다. 문자열을 매개변수로 전달하여 함수를 적용하기만 하면 됩니다. 여기서는 숫자 요소만 고려할 수 있습니다.

예시

import json
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = json.loads(stringA)
# Result and its type
print("final list", res)
print(type(res))

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given string [21,42, 15]
final list [21, 42, 15]

ast.literal_eval 사용

ast 모듈은 문자열을 목록으로 직접 변환할 수 있는 literal_eval을 제공합니다. 문자열을 literal_eval 메소드에 매개변수로 제공하기만 하면 됩니다. 여기서는 숫자 요소만 고려할 수 있습니다.

import ast
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = ast.literal_eval(stringA)
# Result and its type
print("final list", res)
print(type(res))

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given string [21,42, 15]
final list [21, 42, 15]