【问题标题】:How do I identify if a variable is in a list?如何识别变量是否在列表中?
【发布时间】:2021-12-09 14:03:16
【问题描述】:

如何确定随机选择的变量是否在列表中? Python 3

例子:

WarriorList = ['Achilles', 'Sun Wukong']
GuardianList = ['Ares', 'Ymir']
HunterList = ['Apollo', Artemis']
MageList = ['Anubis', 'ra']

Tank = ()

def TankPick():
    Tank = (random.choice(WarriorList))
    print (Tank)

def BalancePick():
    if (Tank) in WarriorList:
        print ('yes')
        print (random.choice(Magelist))
    else:
        print ('no')
        print (random.choice(Hunterlist))

预期结果:

'Sun Wukong'
'yes'
'ra'

'Ymir'
'no'
'Artemis'

【问题讨论】:

  • 您在第 3 行缺少单引号
  • 由于您要寻找的答案并不取决于目标是否是随机的,因此我将删除random 标签。

标签: python-3.x list variables


【解决方案1】:

如何确定随机选择的变量是否在列表中? Python 3

简单:x in y,其中x 是您要检查的元素,y 是您的可迭代值。

不过,您的代码还有一些其他问题。你定义了两个永远不会被调用的函数,它们都没有返回任何值。您有多个 Tank 变量,它们不会像您认为的那样工作。这些变量只存在于定义它们的函数范围内。函数完成后,相应的Tank 变量将被销毁。同时,您在函数之外(在“全局范围”中)声明的那个只被设置为一个空元组,然后永远不会改变,因为其他 Tank 变量再次被限制在它们各自的函数范围内。如果您绝对必须,您应该在函数中将它们声明为 global - 或者,更好的是,正确地将它们用作函数参数和返回值。

【讨论】:

    【解决方案2】:

    我不完全了解您正在努力的最终产品是什么,但我继续努力并尽我所能!

    import random
    WarriorList = ['Achilles', 'Sun Wukong']
    GuardianList = ['Ares', 'Ymir']
    HunterList = ['Apollo', 'Artemis']
    MageList = ['Anubis', 'ra']
    
    class Container:
        def __init__(self):
            self.Tank = ()
        def TankPick(self):
            # Grabs a random name from all of the lists included
            self.Tank = (random.choice(WarriorList + GuardianList + HunterList + MageList))
            print (self.Tank)
    
        def BalancePick(self):
            if self.Tank in WarriorList:
                print ("yes\n" + random.choice(MageList))
                # \n is new line
            else:
                print ("no\n" + random.choice(HunterList))
    
    
    cr = Container()
    # Runs TankPick inside of Container
    cr.TankPick()
    # Runs BalancePick inside of Container after TankPick
    cr.BalancePick()
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2011-02-21
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2020-05-16
      • 2017-01-27
      • 1970-01-01
      相关资源
      最近更新 更多