gpt4 book ai didi

python - 所有组合,而不是使用 if 和 elif

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:45 25 4
gpt4 key购买 nike

除了对以下组合使用多个 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 语句......有什么方法可以做到这一点吗?

最佳答案

这是我的建议:创建所有可能的检查和相应描述符的列表;然后在列表理解中应用检查并选择成功的描述符:

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())

关于python - 所有组合,而不是使用 if 和 elif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com