Python - read numbers from text file and put into list

前端 未结 6 870
日久生厌
日久生厌 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:53

    One-liner:

    [ [int(x) for x in line.split(' ')] for line in open(name,'r').readlines() if line.strip()]
    

    but the readlines part is probably not a great idea.

    I'm quite sure that [int(x) for x in ... ] is faster than using map as in other suggested solutions.

    Edit

    Thanks to Blender : no need for .readlines, which is cool, so we just have :

    [ map(int, line.split()) for line in open(name,'r') if line.strip()]
    

    I also used map(int, ) because it's actually faster, and also you can use just line.split() instead of line.split(' ').

提交回复
热议问题