I want to make a string in a two-dimensional array.

Asked 2 years ago, Updated 2 years ago, 22 views

I'm using Python.
Suppose you have these two-dimensional arrays

data=[18,16,17],[75,50,80],[12,13,14],[8,7,9]]]

I would like to print the contents of this two-dimensional array in a string format as follows. What should I do?

data=[['18', '16', '17', ['75', '50', '80', ['12', '13', '14', ['8', '7', '9']]]

Here's what I've tried:

data=list(map(str,data))
print(data)

If you do this, the output will be as follows:

[[18, 16, 17]', '[7, 5, 8]', '[12, 12, 14]', '[8, 7, 9]']

python

2022-09-30 20:10

1 Answers

There is no approval mark, but this article will be applicable.
convert element of 2D list into string python
(However, this article is based on the assumption that the for loop and join string processing will take place later.)

This is what happens when you apply it.
As I pass the 2D list directly to map(), it looks like a question, so I think it would be better to break it down into a 1D list, apply it, and return it to 2D.

data=[18,16,17],[75,50,80],[12,13,14],[8,7,9]]]

data = [list(map(str,l)) for link data]
print(data)

It seems that the reason why the above introduction article's behavior was not good was because of Python 2.x series descriptions.
This article (converting the question to int) explains it in conjunction with Python 3.x series.
Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?

By the way, it was written in this article that it is better to use double nested list inclusion than combining list() and map().
It looks like this.

data=[18,16,17],[75,50,80],[12,13,14],[8,7,9]]]

data = [[str(e)for e in l] for lin data ]
print(data)

When I looked for the reason, there was an article like this, and it seems that if you want a list as a result, it would be a little faster to include the nested list.
Which is faster, Python map or for inclusion (list inclusion)?


2022-09-30 20:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.