除了为以下组合使用多个if和elif语句之外,还有其他方法:
这是生成我想要的所有组合的代码:
import itertools
a = ['open', 'high', 'low', 'close', 'volume']
for i in range(1,len(a)+1):
print(list(itertools.combinations(a,i)))
[('open',), ('high',), ('low',), ('close',), ('volume',)]
[('open', 'high'), ('open', 'low'), ('open', 'close'), ('open', 'volume'), ('high', 'low'), ('high', 'close'), ('high', 'volume'), ('low', 'close'), ('low', 'volume'), ('close', 'volume')]
[('open', 'high', 'low'), ('open', 'high', 'close'), ('open', 'high', 'volume'), ('open', 'low', 'close'), ('open', 'low', 'volume'), ('open', 'close', 'volume'), ('high', 'low', 'close'), ('high', 'low', 'volume'), ('high', 'close', 'volume'), ('low', 'close', 'volume')]
[('open', 'high', 'low', 'close'), ('open', 'high', 'low', 'volume'), ('open', 'high', 'close', 'volume'), ('open', 'low', 'close', 'volume'), ('high', 'low', 'close', 'volume')]
[('open', 'high', 'low', 'close', 'volume')]
现在我的代码看起来像这样:
if self.average_open.get() and self.average_low.get() and self.average_high.get() and self.average_close.get() and self.average_volume.get():
print("You got Open, Low, High, Close, and Volume")
elif self.average_open.get() and self.average_low.get() and self.average_high and self.average_close.get():
print("You got Open, Low, High, and Close")
elif.........
基本上我必须为生成所有组合的代码中列出的所有组合执行此操作,并且我总共有31个elif语句......有什么方法可以执行此操作吗?
答案 0 :(得分:1)
这是我的建议:创建所有可能检查和相应描述符的列表;然后在列表推导中应用检查并选择成功的描述符:
actions = [(self.average_open.get, "Open"), (self.average_low.get, "Low"),\
(self.average_high.get, "High"), (self.average_close.get, "Close"),\
(self.average_volume.get, "Volume")]
print("You got " + ", ".join(word for fun,word in actions if fun())
答案 1 :(得分:0)
你可以使用这样的东西来创建你要打印的字符串:
def createMessage():
switches = [self.average_open.get(), self.average_low.get(), self.average_height.get(), self.average_close.get(), self.average_volume.get()]
options = ["Open", "Low", "Height", "Close", "Volume"]
gotten = []
for switch, option in zip(switches, options):
if switch:
gotten.append(option)
return "You got " + ", ".join(gotten)