将嵌套列表转换为字符串

5
如何将以下的list转换为string
list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]

Result: '1 1 1'
        '2 2 2'
        '3 3 3'

谢谢


我删除了Python标签,因为它不是由发布者放置的,正如其他人指出的那样,它可能是Ruby。 - Colin Burnett
谢谢 Colin,是我的错误。最近我也在写一些 Ruby 代码! - mechanical_meat
7个回答

9

看起来像是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']

1
join()中不需要使用方括号,可以这样写:' '.join(str(c) for c in lst) 或者 ' '.join(map(str, lst)) - jfs

3

更快、更简单的方式:

Result = " ".join([' '.join([str(c) for c in lst]) for lst in list1])

1
你可以在每个数组上调用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

这个循环遍历每个组。它使用空格连接组,然后用单引号包裹起来。每个组都保存在一个数组中,这有助于下一步的格式化。

与之前一样,字符串使用空格连接。然后打印结果。


Chris,Python标签不是由发布者放置的。我已经将其删除,因为像你和cloudhead所假设的那样,它可能是Ruby。 - Colin Burnett
对于混淆问题我道歉。我添加了Python标签,感谢Colin的移除。 - mechanical_meat

1
这是一行代码。
>>> print "'"+"' '".join(map(lambda a:' '.join(map(str, a)), list1))+"'"
'1 1 1' '2 2 2' '3 3 3'

0
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

请考虑在您的代码/答案中添加细节,以便其他人也可以从您的答案中受益。 - rcanpahali

-1

也可能是Ruby,这种情况下你可以这样做:

list = [[1, '1', 1], [2,'2',2], [3,'3',3]]
list.join(' ')

这将导致输出 "1 1 1 2 2 2 3 3 3"


-1
最终得到了这个:
for a, b, c in data:
    print(repr(a)+' '+repr(b)+' '+repr(c))

我必须将输出写入一个 textfile,其中 write() 方法只能接受类型为 str 的参数,这就是 repr() 函数派上用场的地方。

repr()- Input: object; Output: str

...我应该说明我在使用Python编程...感谢您的建议


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接