简体   繁体   中英

Nested for loops in list comprehension

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 python. This is my code.

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

How can I do this in one line using nested for loops.

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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM