'Problems converting a list comprehension
This list comprehension works, but I’d rather have it written like conventional loops:
Here is the list comprehension:
with open(sys.argv[1], 'r') as f:
x = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ]
Here's what I've tried so far:
with open(sys.argv[1], 'r') as f:
x = []
for line in f:
for num in line:
if line.strip() != '':
x.append((num))
What I tried doesn't work. First off, I don't know where to add the split(',') line and I’m not sure where I can get num to be integers.
Solution 1:[1]
It would be more like:
with open(sys.argv[1], "r") as f:
x = []
for line in f:
if not line.strip():
# Skip this line
continue
inner_list = []
for num in line.split(","):
inner_list.append(int(num))
x.append(inner_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul M. |
