dimanche 6 décembre 2020

Python For Loop One Line Syntax

I have several classes with I am initializing using csv files as input. The csv file is read in and initializes objects by:

input_file  = open(sys.argv[1], 'r')
csv_file = csv.reader(input_file)

for line in csv_file:
    if line[0] == "object":
        objects.append(object(line));

One of these classes is defined as:

class object:
    def __init__(self,line):
        self.type = line[1]
        self.list = ....

I need to fill the list in a fashion such that it follows the following logic:

if line[1] == 'a':
    for element in line[4:15]:
         self.list.append(element)

Essentially, I want to fill up the list with elements 4 through 14 if the type is 'a', but otherwise leave it empty. Is there a way I can turn the if and for loop into a one line piece of code to fill the list (or not) during initialization? Or really any way I could fill the list during initialization.

I'm sorry I don't really work with python and haven't picked up the syntax perfectly yet as I am mostly used to working with C and C++ nowadays.

Any help would be much appreciated.

edit: syntax

Aucun commentaire:

Enregistrer un commentaire