'convert nested lists to string

How can I convert the following list to a string?

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

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

Thanks



Solution 1:[1]

Looks like Python. List comprehensions make this easy:

list1= [[1, '1', 1], [2,'2',2], [3,'3',3]]
outlst = [' '.join([str(c) for c in lst]) for lst in list1]

Output:

['1 1 1', '2 2 2', '3 3 3']

Solution 2:[2]

Faster and Easier way:

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

Solution 3:[3]

You could call join on each of the arrays. Ex:

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

This loops through each of the groups. It joins the groups with a space, then wraps it in single quotes. Each of these groups are saved into an array, this helps formatting in the next step.

Like before the strings are joined with a space. Then the result is printed.

Solution 4:[4]

here is a one liner

>>> print "'"+"' '".join(map(lambda a:' '.join(map(str, a)), list1))+"'"
'1 1 1' '2 2 2' '3 3 3'

Solution 5:[5]

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)))

Output:

a, b, c, d, e, g, h, i, j, k, l

Solution 6:[6]

Could be ruby too, in which case you'd do something like:

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

which would result in "1 1 1 2 2 2 3 3 3"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Colin Burnett
Solution 2 Omkar
Solution 3 manlycode
Solution 4 Anurag Uniyal
Solution 5 S.B
Solution 6 cloudhead