Reputation:
I have a 2D list containing all integers. I want to convert all integer into string:
L = [[1,2,3,4,5],[6,7,8,9,10]]
L = [['1','2','3','4','5'],['6','7','8','9','10']] # convert into string.
Now print them out like following format:
1 -> 2 -> 3 -> 4 -> 5
6 -> 7 -> 8 -> 9 -> 10
I tried using these codes:
final_out = [i for i in final_out str(ii) for ii in i]
It does not works.
Upvotes: 1
Views: 2873
Reputation: 2480
You can also do that using nested loop
:
>>> L = [[1,2,3,4,5],[6,7,8,9,10]]
>>> new_L = [[str(j) for j in i] for i in L]
>>> new_L
[['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10']]
>>> for i in new_L:
print ' -> '.join(i)
1 -> 2 -> 3 -> 4 -> 5
6 -> 7 -> 8 -> 9 -> 10
>>>
Upvotes: 0
Reputation: 48067
You can use map
function for this:
>>> L = [[1,2,3,4,5],[6,7,8,9,10]]
>>> L = [map(str, l) for l in L] # Convert into list of 'str'
>>> L
[['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10']]
>>> for l in L:
... print ' -> '.join(l)
...
1 -> 2 -> 3 -> 4 -> 5
6 -> 7 -> 8 -> 9 -> 10
Simpler way to write the above code is:
>>> L = [[1,2,3,4,5],[6,7,8,9,10]]
>>> for l in L:
... print ' -> '.join(map(str, l))
Upvotes: 2
Reputation: 20336
Do this:
print("\n".join(" -> ".join(str(num) for num in sub) for sub in L))
Output:
1 -> 2 -> 3 -> 4 -> 5
6 -> 7 -> 8 -> 9 -> 10
Since I used str(num)
, you can just keep L
the same. That is, you don't need to convert them to integers.
Upvotes: 0