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
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
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']
join() it could be: ' '.join(str(c) for c in lst) or ' '.join(map(str, lst)).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.
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
ended up with this:
for a, b, c in data:
print(repr(a)+' '+repr(b)+' '+repr(c))
i had to write the output to a textfile, in which the write() method could only take type str, this is where the repr() function came in handy
repr()- Input: object; Output: str
...shoulda stated I was working in Python tho...thanks for the input