Converting a string into a list in Python

后端 未结 5 824
孤独总比滥情好
孤独总比滥情好 2021-01-12 01:06

I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want

5条回答
  •  北海茫月
    2021-01-12 01:31

    To convert a Python string into a list use the str.split method:

    >>> '1000 2000 3000 4000'.split()
    ['1000', '2000', '3000', '4000']
    

    split has some options: look them up for advanced uses.

    You can also read the file into a list with the readlines() method of a file object - it returns a list of lines. For example, to get a list of integers from that file, you can do:

    lst = map(int, open('filename.txt').readlines())
    

    P.S: See some other methods for doing the same in the comments. Some of those methods are nicer (more Pythonic) than mine

提交回复
热议问题