0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
robothead
  • 303
  • 2
  • 10
  • see [if/else in a list comprehension](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – AcK May 07 '22 at 01:52

1 Answers1

2

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)
        
Paul M.
  • 10,481
  • 2
  • 9
  • 15