I'm a python newb and am having trouble groking nested list comprehensions. I'm trying to write some code to read in a file and construct a list for each character for each line.
so if the file contains
xxxcd
cdcdjkhjasld
asdasdxasda
The resulting list would be:
[
['x','x','x','c','d']
['c','d','c','d','j','k','h','j','a','s','l','d']
['a','s','d','a','s','d','x','a','s','d','a']
]
I have written the following code, and it works, but I have a nagging feeling that I should be able to write a nested list comprehension to do this in fewer lines of code. any suggestions would be appreciated.
data = []
f = open(file,'r')
for line in f:
line = line.strip().upper()
list = []
for c in line:
list.append(c)
data.append(list)
This should help (you'll probably have to play around with it to strip the newlines or format it however you want, but the basic idea should work):
f = open(r"temp.txt")
[[c for c in line] for line in f]
In your case, you can use the list
constructor to handle the inner loop and use list comprehension for the outer loop. Something like:
f = open(file)
data = [list(line.strip().upper()) for line in f]
Given a string as input, the list constructor will create a list where each character of the string is a single element in the list.
The list comprehension is functionally equivalent to:
data = []
for line in f:
data.append(list(line.strip().upper()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With