vendredi 27 novembre 2020

How can I make a long if else and strings generic?

I have a value_list which is created generic and this value_list includes something like this:

['C','E','F'] # this always changes

Now I have to write into a file which of these rules where attached in value_list.

I saved all my rules in all rules.

all_rules = ['A', 'B', 'C', 'D', 'E', 'F'] #this can also change so thats why i have to do it generic

First I did something like this and this works but I want to do it generic:

marked_rule = ["-", "-", "-", "-", "-", "-"]

        for value in value_list:
            if value == "A":
                marked_rule [0] = "X"
            elif value == "B":
                marked_rule [1] = "X"
            elif value == "C":
                marked_rule [2] = "X"
            elif value == "D":
                marked_rule [3] = "X"
            elif value == "E":
                marked_rule [4] = "X"
            elif value == "F":
                marked_rule [5] = "X"

new_line= "{:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1}".format(*marked_rule)

Here it write into file

Output:

A B C D E F  
- - X - X X #marked_rule should look like this ["-" "-" "X" "-" "X" "X"].

TODO: make it generic:

first I want to do these lines as often as my all_rules list is

marked_rule = ["-", "-", "-", "-", "-", "-"]

Next I want to add without writing these hard coded If clauses

Frist try, but does not work:

        for index, value in enumerate (value_list):
            if value == all_rules [index]:
                marked_rule[index] = "X"

Next also want to do the string formatting generic, so it shoud contain so many {:-<1} as much as the index of all_rules. The problem is I add somethig before and after (these are fix) . In real case it looks like this:

" *  {:<10} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:<23} {:<3}"

Aucun commentaire:

Enregistrer un commentaire