Nested for loops in list comprehension

后端 未结 1 1473
庸人自扰
庸人自扰 2021-01-26 16:00

I\'m new to python and just trying to learn how to make my code more pythonic. I\'m reading a file into a list of strings and then reading these strings into their own list in p

1条回答
  •  孤街浪徒
    2021-01-26 16:26

    The for clauses go in the same order as if you had written a nested loop.

    data = [list(item) for line in open(filename, 'r') for item in line.strip()]
    

    You should be using a with statement, though:

    with open(filename, 'r') as f:
        data = [list(item) for line in f for item in line.strip()]
    

    0 讨论(0)
提交回复
热议问题