【问题标题】:How to convert comma-delimited string to list in Python?如何将逗号分隔的字符串转换为 Python 中的列表?
【发布时间】:2011-12-12 05:56:50
【问题描述】:

给定一个字符串,该字符串是由逗号分隔的多个值的序列:

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

如何将字符串转换为列表?

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

【问题讨论】:

标签: python parsing list tuples


【解决方案1】:

你可以使用 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']

【讨论】:

  • 小心,拆分一个空字符串不会返回预期的结果:"".split(",") 返回[""](一个包含一个元素的列表,它是空字符串)。
【解决方案2】:
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')

【讨论】:

    【解决方案3】:

    对于字符串中包含的整数,如果您想避免将它们单独转换为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]
    

    【讨论】:

      【解决方案4】:

      您可以使用此功能将逗号分隔的单个字符串转换为列表-

      def stringtolist(x):
          mylist=[]
          for i in range(0,len(x),2):
              mylist.append(x[i])
          return mylist
      

      【讨论】:

        【解决方案5】:
        #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)
        

        【讨论】:

          【解决方案6】:

          为了处理空字符串的情况,请考虑以下几点:

          >>> 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 []
          []
          

          【讨论】:

            【解决方案7】:

            你可以在,上拆分那个字符串,直接得到一个列表:

            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')

            【讨论】:

            • 希望它能解决问题,但请添加对代码的解释,以便用户完全理解他/她真正想要的。
            • 看起来像 already accepted 答案的副本(9 年前)。
            猜你喜欢
            • 1970-01-01
            • 2023-04-02
            • 2013-02-04
            • 1970-01-01
            • 1970-01-01
            • 2021-01-23
            • 1970-01-01
            • 1970-01-01
            • 2018-02-22
            相关资源
            最近更新 更多