Home >Backend Development >Python Tutorial >How to convert python string to two-dimensional array

How to convert python string to two-dimensional array

php中世界最好的语言
php中世界最好的语言Original
2018-04-09 09:38:067722browse

This time I will bring you pythonstringhow to convert two-dimensional array, python string to two-dimensional arraynote What are the matters? Below are practical cases. Let’s take a look.

There is an algorithm question that means to find a peak in a two-dimensional array. The required complexity is n.

The idea of ​​​​solving the problem is to find the maximum value among the Tian characters (the four sides and the two horizontal and vertical lines in the middle), and use the divide-and-conquer method RecursionThe Tian characters in the next quadrant.

When using python to define a two-dimensional array, there are two ways: list and numpy.array. After reading several blogs about the creation of two-dimensional arrays in python, I found that most of them are initialized two-dimensional arrays. , and what I need to read from the file is a string, and then convert the string into a two-dimensional array. If I can't find a solution, I decide to convert it myself.

First of all, the initial string output is as follows, with spaces between the numbers

The idea is First slice according to the newline character, and then perform another slicing operation on the characters of each line. The code is as follows:

But in fact I am using "\n" to do it When slicing, a small "" empty tail is left at the end. It may be that there is a newline character at the end of the text, so I used list.pop() on line 9 to remove the empty element. (Not required in window environment)

In this way, you can get the two-dimensional array of list, because of numpy. Array supports more indexing methods than list. We use list = np.array(list) to convert list to numpy.array. The final result is as follows:

That’s it. After the conversion is completed, the next step is to write algorithms to solve problems. Generally speaking, I am still not satisfied with my method. If there is a more elegant method for converting two-dimensional arrays, please leave a message. I will be grateful~

I believe you have mastered the method after reading the case in this article. More Please pay attention to other related articles on the php Chinese website!

Recommended reading:

The object of diff is the listening event of virtual dom

##Event emitter

The above is the detailed content of How to convert python string to two-dimensional array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn