'list'中的'value'在哪里

时间:2018-01-31 06:49:08

标签: python-3.x list dictionary

我希望缩短这段代码:

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个元素。

另外,我真的不喜欢使用嵌套循环,我发现它们在从代码中短暂中断后变得难以阅读和调试,并且它们很容易使用大量的空间和时间。我不会有很长的清单,但我可能会有很多卡片,所以如果有一个简单的选择,我宁愿使用它。

1 个答案:

答案 0 :(得分:2)

可以简化为此。

char_list = ['W', 'U', 'B', 'R', 'G']
for i in card.get_mana_cost():
    match_colors = i in char_list and color[char_list.index(i)] is not 0

重要的是char_list.index。它返回i中的char_list索引。