如何使用漂亮的分隔符在python中将列表元组列表转换为字符串

问题描述

|| 将列表/元组列表转换为带有增量缩进的字符串的最佳方法是什么? 到目前为止,我已经有了这样的功能
def a2s(a,inc = 0):
    inc += 1
    sep = \' \' * inc
    if type(a) == type(list()) or type(a) == type(tuple()):
        a = sep.join(map(a2s,a))
    else:
       a = str(a)
   return a
它会给
>>> a=[[1,2],[3,4]]
>>> a2s(a)
\'1 2 3 4\'
所以问题是如何使
[1,2]
[3,4]
之间的增量更大,像这样
>>> a2s(a)
\'1 2  3 4\'
是否有任何方法通过map函数传递不可迭代的\'inc \'参数?还是其他方式可以做到这一点?     

解决方法

        这是您需要的:
import collections

def a2s(a):
    res = \'\'
    if isinstance(a,collections.Iterable):
        for item in a:
            res +=  str(a2s(item)) + \' \'
    else:
        res = str(a)
    return res
用法:
a = [ [1,2],[3,4] ]
print(a2s(a))
>>> 1 2  3 4
递归岩! :)     ,        您可以通过以下方式修改您的函数:
def list_to_string(lVals,spacesCount=1):
    for i,val in enumerate(lVals):
        strToApp = \' \'.join(map(str,val))
        if i == 0:
            res = strToApp 
        else:
            res += \' \' * spacesCount + strToApp
    return res

print list_to_string(a)# \'1 2 3 4\'
print list_to_string(a,2)# \'1 2  3 4\'
print list_to_string(a,3)# \'1 2   3 4\'
还是有点怪,但是:
from collections import Iterable

data = [[1,4],[5,6],7]

def list_to_string(lVals,spacesCount=3):
    joinVals = lambda vals: \' \'.join(map(str,vals)) if isinstance(vals,Iterable) else str(vals)
    return reduce(lambda res,x: joinVals(res) + (\' \' * spacesCount) + joinVals(x),lVals)

list_to_string(data,4)
并且最好使用\'isinstance \'而不是\'type(val)== type(list())\',或者您可以在[list,tuple,set] \中使用\'type(val)\' 。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...