1

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}"
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
BMWe30
  • 45
  • 4
  • 1
    Does this answer your question? [Most efficient way of making an if-elif-elif-else statement when the else is done the most?](https://stackoverflow.com/questions/17166074/most-efficient-way-of-making-an-if-elif-elif-else-statement-when-the-else-is-don) – mkrieger1 Nov 27 '20 at 09:49
  • 1
    I have seen this post before, but I have a different case. I coulndt solve it. Could you maybe help me ? – BMWe30 Nov 27 '20 at 09:51

1 Answers1

1

You might use list-comprehension combined with ternary if for that task i.e.:

rules = ['C','E','F']
all_rules = ['A', 'B', 'C', 'D', 'E', 'F']
marked_rule = ['X' if i in rules else '-' for i in all_rules]
print(marked_rule)

Output:

['-', '-', 'X', '-', 'X', 'X']

Then use .join to get string out of it - this will work with any number of arguments:

output = ' '.join(marked_rule)
print(output)

Output:

- - X - X X
Daweo
  • 31,313
  • 3
  • 12
  • 25