我怎样才能使 long if else 和 strings 通用?
How can I make a long if else and strings generic?
我有一个 value_list 是通用的,这个 value_list 包括这样的东西:
['C','E','F'] # this always changes
现在我必须将这些规则中的哪些附加到文件中 value_list。
我在所有规则中保存了我的所有规则。
all_rules = ['A', 'B', 'C', 'D', 'E', 'F'] #this can also change so thats why i have 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)
这里写入文件
输出:
A B C D E F
- - X - X X #marked_rule should look like this ["-" "-" "X" "-" "X" "X"].
待办事项:使其通用:
首先,我想像我的 all_rules 列表一样频繁地执行这些行
marked_rule = ["-", "-", "-", "-", "-", "-"]
接下来我想在不编写这些硬编码 If 子句的情况下添加
第一次尝试,但没有用:
for index, value in enumerate (value_list):
if value == all_rules [index]:
marked_rule[index] = "X"
接下来还要做字符串格式化泛型,所以应该包含{:-<1}
和all_rules的索引一样多。问题是我在之前和之后添加了一些东西(这些是修复的)。在实际情况下,它看起来像这样:
" * {:<10} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:<23} {:<3}"
您可以使用 list
-comprehension 结合三元 if
来完成该任务,即:
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)
输出:
['-', '-', 'X', '-', 'X', 'X']
然后使用 .join
从中获取字符串 - 这将适用于任意数量的参数:
output = ' '.join(marked_rule)
print(output)
输出:
- - X - X X
我有一个 value_list 是通用的,这个 value_list 包括这样的东西:
['C','E','F'] # this always changes
现在我必须将这些规则中的哪些附加到文件中 value_list。
我在所有规则中保存了我的所有规则。
all_rules = ['A', 'B', 'C', 'D', 'E', 'F'] #this can also change so thats why i have 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)
这里写入文件
输出:
A B C D E F
- - X - X X #marked_rule should look like this ["-" "-" "X" "-" "X" "X"].
待办事项:使其通用:
首先,我想像我的 all_rules 列表一样频繁地执行这些行
marked_rule = ["-", "-", "-", "-", "-", "-"]
接下来我想在不编写这些硬编码 If 子句的情况下添加
第一次尝试,但没有用:
for index, value in enumerate (value_list):
if value == all_rules [index]:
marked_rule[index] = "X"
接下来还要做字符串格式化泛型,所以应该包含{:-<1}
和all_rules的索引一样多。问题是我在之前和之后添加了一些东西(这些是修复的)。在实际情况下,它看起来像这样:
" * {:<10} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:<23} {:<3}"
您可以使用 list
-comprehension 结合三元 if
来完成该任务,即:
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)
输出:
['-', '-', 'X', '-', 'X', 'X']
然后使用 .join
从中获取字符串 - 这将适用于任意数量的参数:
output = ' '.join(marked_rule)
print(output)
输出:
- - X - X X