【问题标题】:Where is 'value' in 'list'“列表”中的“价值”在哪里
【发布时间】: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


【解决方案1】:

可以简化成这样。

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。它返回ichar_list 中的索引。

【讨论】:

  • card.get_mana_cost() 可能会比char_list 短。我可能应该提到这一点,但.index 是我将继续阅读的内容。谢谢
  • @Maxia get_mana_cost 的长度在这里无所谓吧?
  • @Maxia 顺便说一句,如果您认为我的回答回答了您的问题,请考虑通过单击该复选标记接受它!
  • 如果 card.get_mana_cost() 中有 3 个元素,那么 i in char_list 是否只能检查到 'B'?除非i 是一个元素,而不是一个计数器,这看起来更像是pythonic。
  • @Maxia in 只是检查i 是否在列表中。 i一个元素。
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
相关资源
最近更新 更多