Reading a file into a multidimensional array with Python

前端 未结 5 1332
迷失自我
迷失自我 2021-02-20 02:56

If I have a text file like this:

Hello World
How are you?
Bye World

How would I read it into a multidimensional array like this:



        
5条回答
  •  既然无缘
    2021-02-20 03:23

    You can use map with the unbound method str.split:

    >>> map(str.split, open('testFile.txt'))
    [['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
    

    In Python 3.x, you have to use list(map(str.split, ...)) to get a list because map in Python 3.x return an iterator instead of a list.

提交回复
热议问题