Python - read numbers from text file and put into list

前端 未结 6 866
日久生厌
日久生厌 2020-12-03 16:12

So like the title says im starting to learn some python and im having trouble picking up on this technique. What I need to accomplish is to read in some numbers and store t

6条回答
  •  旧巷少年郎
    2020-12-03 16:48

    Assuming there isn't actually a blank line in your input file:

    with open(name, "r") as infile:
        polyShape = [map(int, line.split()) for line in infile]
    

    Explanation: map(int, line.split()) splits each line and converts each part to an int. The [X for Y in Z] construct is a list comprehension that in turn maps the map over all lines of the file and returns its results in a list.

    If you find this too complicated for now, then the map(int, line.split()) is the main take-home message.

提交回复
热议问题