5

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

2
  • I removed the python tag because it was not put there by the poster and as others have pointed out it could be Ruby. Commented Jun 10, 2009 at 3:45
  • Thanks Colin, my mistake. And I have been doing a little Ruby coding lately too! Commented Jun 10, 2009 at 3:49

7 Answers 7

9

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']
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need in square brackets inside join() it could be: ' '.join(str(c) for c in lst) or ' '.join(map(str, lst)).
3

Faster and Easier way:

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

Comments

1

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.

2 Comments

Chris, the Python tag wasn't put there by the poster. I have removed it since it, as you and cloudhead assumed, could be Ruby.
My apologies for the confusion. I added the Python tag. Thanks to Colin for removing.
1

here is a one liner

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

Comments

1
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

1 Comment

Please consider adding details in your codes/answers, so others can also benefit from your answer.
-1

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"

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.