【发布时间】:2018-01-31 06:49:07
【问题描述】:
我希望缩短这段代码:
for i in card.get_mana_cost():
if i is 'W' and colors[0] is not 0:
match_colors = True
elif i is 'U' and colors[1] is not 0:
match_colors = True
elif i is 'B' and colors[2] is not 0:
match_colors = True
elif i is 'R' and colors[3] is not 0:
match_colors = True
elif i is 'G' and colors[4] is not 0:
match_colors = True
我能想到的最好方法是将我的字符放在symbols = ['W', 'U', 'B', 'R', 'G'] 之类的列表中
然后我想以颜色达到的索引将始终与符号索引相同,但我不知道如何检查哪个索引触发了in 以返回True。
我尝试使用 zip 创建带有 [symbols: colors] 的字典,但我仍然需要找到索引,所以我检查正确的值不是 0。
编辑
card.get_mana_cost() 返回一个不同大小的字符串列表。通常它只会包含 2 或 3 个元素。
另外,我真的不喜欢使用嵌套循环,我发现它们在代码短暂中断后变得难以阅读和调试,而且它们很容易占用大量空间和时间。我不会有很长的清单要浏览,但我可能有很多卡片,所以如果有一个简单的替代方案,我宁愿使用它。
【问题讨论】:
-
您的代码中的
card.get_mana_cost()是什么? -
这是一个不同长度的列表
标签: python-3.x list dictionary