【问题标题】:Convert a list into a string and allow for a separator将列表转换为字符串并允许使用分隔符
【发布时间】:2016-10-02 22:39:20
【问题描述】:

请注意,我是 python 新手: 我正在尝试创建一个已定义的函数,该函数可以将列表转换为字符串,并允许我放入分隔符。分隔符必须是“,”。 我目前的思考过程是将列表中的每个项目添加到一个空字符串变量中,然后我试图利用 range 函数在其中添加一个分隔符。我只想使用 str() 和 range( )。

def list2Str(lisConv, sep = ', '):
    var = ''
    for i in lisConv:
        var = var + str(i)
        #test line
        print(var, "test line")
    var1 = int(var)
    for a in range(var1):
        print(str(var1)[a],  sep = ', ')

list1 = [2,0,1,6]        

result = list2Str(list1, ', ')
print(result)

【问题讨论】:

    标签: python string list function


    【解决方案1】:

    首先您需要将 int 列表转换为字符串列表。

    您可以使用列表理解:https://docs.python.org/3/tutorial/datastructures.html

    str_list = [str(x) for x in list1]
    

    然后,用你想要的分隔符加入字符串列表。

    sep = ', '
    print(sep.join(str_list))
    

    以更简洁的方式:

    print(', '.join([str(x) for x in [1, 2, 3]))
    

    更多关于加入的信息:http://www.diveintopython.net/native_data_types/joining_lists.html

    【讨论】:

    【解决方案2】:
    list=['asdf', '123', 'more items...']
    print ', '.join([str(x) for x in list])
    

    如果您想创建自己的函数进行转换,您可以执行以下操作。

    def convert(list, sep):
        n_str = ''
        for index, I in enumerate(list): #enumerate(list) returns (current position, list[current position]) so if we need to know the current position we use enumerate
            if index != len(list)-1:
                n_str += str(i) + sep #we don't apply the seperator if we're at the end of the list
            else:
                n_str += str(i)
        return n_str
    

    【讨论】:

    • 如果列表中的项目不是字符串怎么办?
    • 我要操作的列表不一定是字符串,这就是为什么我包含代码来尝试创建字符串,然后想要包含分隔符。仅供参考,这是作业,我们不允许使用字符串方法
    • 好的。这篇文章已经过编辑,包含一个将列表转换为字符串的函数,列表中的每个项目用 sep 分隔。
    • 关于我的代码(出于学习目的),第二个解释更符合我的要求简单吗?
    • 我重写你的函数的原因是因为它试图做太多事情(即你的调试语句和变量使函数混乱)如果你想打印结果你可以print(convert(list, ', '))
    【解决方案3】:

    如果不允许使用字符串方法(如join),reduce 应该提供最短的解决方案:

    def list2Str(lisConv, sep = ', '):
        return reduce(lambda x, y: str(x) + sep + str(y), lisConv)
    
    print(list2Str([2, 0, 1, 6], ', '))
    # 2, 0, 1, 6
    

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2013-03-09
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多