5

如何将以下内容转换liststring

list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]

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

谢谢

4

7 回答 7

8

看起来像 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']
于 2009-06-10T03:37:35.413 回答
2

更快更简单的方法:

Result = " ".join([' '.join([str(c) for c in lst]) for lst in list1])
于 2020-09-12T19:54:34.133 回答
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

这循环通过每个组。它用空格连接组,然后用单引号括起来。这些组中的每一个都保存到一个数组中,这有助于下一步的格式化。

就像在字符串用空格连接之前一样。然后打印结果。

于 2009-06-10T03:43:02.123 回答
1

这是一个班轮

>>> print "'"+"' '".join(map(lambda a:' '.join(map(str, a)), list1))+"'"
'1 1 1' '2 2 2' '3 3 3'
于 2009-06-10T03:49:13.467 回答
0

结束了这个:

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 工作...感谢您的输入

于 2009-06-11T12:42:42.343 回答
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
于 2021-09-16T00:58:20.553 回答
-2

也可能是红宝石,在这种情况下你会做类似的事情:

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

这将导致“1 1 1 2 2 2 3 3 3”

于 2009-06-10T03:42:46.273 回答