如何将以下的
list
转换为string
?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']
join()
中不需要使用方括号,可以这样写:' '.join(str(c) for c in lst)
或者 ' '.join(map(str, lst))
。 - jfs更快、更简单的方式:
Result = " ".join([' '.join([str(c) for c in lst]) for lst in list1])
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
这个循环遍历每个组。它使用空格连接组,然后用单引号包裹起来。每个组都保存在一个数组中,这有助于下一步的格式化。
与之前一样,字符串使用空格连接。然后打印结果。
>>> print "'"+"' '".join(map(lambda a:' '.join(map(str, a)), list1))+"'"
'1 1 1' '2 2 2' '3 3 3'
def get_list_values(data_structure, temp=[]):
for item in data_structure:
if type(item) == list:
temp = get_list_values(item, temp)
else:
temp.append(item)
return temp
nested_list = ['a', 'b', ['c', 'd'], 'e', ['g', 'h', ['i', 'j', ['k', 'l']]]]
print(', '.join(get_list_values(nested_list)))
输出:
a, b, c, d, e, g, h, i, j, k, l
也可能是Ruby,这种情况下你可以这样做:
list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
list.join(' ')
这将导致输出 "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编程...感谢您的建议