如何将以下内容转换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']
更快更简单的方法:
Result = " ".join([' '.join([str(c) for c in lst]) for lst in list1])
您可以在每个阵列上调用 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
这循环通过每个组。它用空格连接组,然后用单引号括起来。这些组中的每一个都保存到一个数组中,这有助于下一步的格式化。
就像在字符串用空格连接之前一样。然后打印结果。
这是一个班轮
>>> 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))
我必须将输出写入 a textfile
,其中 write() 方法只能采用 type str
,这是该repr()
函数派上用场的地方
repr()- Input: object; Output: str
...应该说我正在使用 Python 工作...感谢您的输入
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
也可能是红宝石,在这种情况下你会做类似的事情:
list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
list.join(' ')
这将导致“1 1 1 2 2 2 3 3 3”