String 将嵌套列表转换为字符串
如何将以下String 将嵌套列表转换为字符串,string,list,nested,String,List,Nested,如何将以下列表转换为字符串 list1= [[1, '1', 1], [2,'2',2], [3,'3',3]] Result: '1 1 1' '2 2 2' '3 3 3' 谢谢看起来像Python。列表理解使这变得简单: list1= [[1, '1', 1], [2,'2',2], [3,'3',3]] outlst = [' '.join([str(c) for c in lst]) for lst in list1] 输出: ['1 1 1',
列表
转换为字符串
list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]
Result: '1 1 1'
'2 2 2'
'3 3 3'
谢谢看起来像Python。列表理解使这变得简单:
list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]
outlst = [' '.join([str(c) for c in lst]) for lst in list1]
输出:
['1 1 1', '2 2 2', '3 3 3']
也可以是ruby,在这种情况下,您可以执行以下操作:
list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
list.join(' ')
这将导致“1 1 2 3 3”您可以在每个数组上调用join。例:
list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]
stringified_groups = []
list1.each do |group|
stringified_groups << "'#{group.join(" ")}'"
end
result = stringified_groups.join(" ")
puts result
list1=[[1,'1',1],[2,'2',2],[3,'3',3]]
字符串化组=[]
清单1.每个do |组|
字符串化组这是一条直线
>>> print "'"+"' '".join(map(lambda a:' '.join(map(str, a)), list1))+"'"
'1 1 1' '2 2 2' '3 3 3'
结果是:
for a, b, c in data:
print(repr(a)+' '+repr(b)+' '+repr(c))
我必须将输出写入一个textfile
,其中write()方法只能采用类型str
,这就是repr()
函数派上用场的地方
repr()- Input: object; Output: str
…应该说我在用Python tho工作…感谢您的输入更快更简单的方法:
Result = " ".join([' '.join([str(c) for c in lst]) for lst in list1])
我删除了python标记,因为它没有放在海报上,正如其他人指出的,它可能是Ruby。谢谢Colin,我的错误。我最近也在做一些Ruby编码!克里斯,海报上没有放Python标签。我已经删除了它,因为正如你和cloudhead所认为的,它可能是Ruby。我为混淆道歉。我添加了Python标记。多亏了科林的删除。在join()
中不需要方括号,它可以是:'.join(str(c)表示lst中的c)
或'.join(map(str,lst))
。