programing

Python에서 쉼표로 구분된 문자열을 목록으로 변환하는 방법은 무엇입니까?

randomtip 2022. 11. 22. 22:11
반응형

Python에서 쉼표로 구분된 문자열을 목록으로 변환하는 방법은 무엇입니까?

콤마로 구분된 여러 값의 시퀀스 문자열 지정:

mStr = 'A,B,C,D,E' 

문자열을 목록으로 변환하려면 어떻게 해야 합니까?

mList = ['A', 'B', 'C', 'D', 'E']

str.split 메서드를 사용할 수 있습니다.

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

태플로 변환하고 싶다면

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

목록에 추가할 경우 다음을 수행하십시오.

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']

문자열에 포함된 정수의 경우, 정수의 캐스팅을 피하려면int개별적으로 다음을 수행할 수 있습니다.

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

이것은 리스트 이해라고 불리며, 세트 빌더 표기법에 근거하고 있습니다.

예:

>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]

빈 문자열의 경우를 처리하려면 다음 사항을 고려하십시오.

>>> my_string = 'A,B,C,D,E'
>>> my_string.split(",") if my_string else []
['A', 'B', 'C', 'D', 'E']
>>> my_string = ""
>>> my_string.split(",") if my_string else []
[]
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')

이 문자열은 위에서 분할할 수 있습니다.,목록을 직접 얻을 수 있습니다.

mStr = 'A,B,C,D,E'
list1 = mStr.split(',')
print(list1)

출력:

['A', 'B', 'C', 'D', 'E']

n 태플로 변환할 수도 있습니다.

print(tuple(list1))

출력:

('A', 'B', 'C', 'D', 'E')

이 함수를 사용하여 쉼표로 구분된 단일 문자열을 목록으로 변환할 수 있습니다.

def stringtolist(x):
    mylist=[]
    for i in range(0,len(x),2):
        mylist.append(x[i])
    return mylist
#splits string according to delimeters 
'''
Let's make a function that can split a string
into list according the given delimeters. 
example data: cat;dog:greff,snake/
example delimeters: ,;- /|:
'''
def string_to_splitted_array(data,delimeters):
    #result list
    res = []
    # we will add chars into sub_str until
    # reach a delimeter
    sub_str = ''
    for c in data: #iterate over data char by char
        # if we reached a delimeter, we store the result 
        if c in delimeters: 
            # avoid empty strings
            if len(sub_str)>0:
                # looks like a valid string.
                res.append(sub_str)
                # reset sub_str to start over
                sub_str = ''
        else:
            # c is not a deilmeter. then it is 
            # part of the string.
            sub_str += c
    # there may not be delimeter at end of data. 
    # if sub_str is not empty, we should att it to list. 
    if len(sub_str)>0:
        res.append(sub_str)
    # result is in res 
    return res

# test the function. 
delimeters = ',;- /|:'
# read the csv data from console. 
csv_string = input('csv string:')
#lets check if working. 
splitted_array = string_to_splitted_array(csv_string,delimeters)
print(splitted_array)

언급URL : https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python

반응형