【问题标题】:ValueError: not in the listValueError:不在列表中
【发布时间】:2021-04-11 12:02:53
【问题描述】:

我是 Python 的初学者,在从列表中获取索引时遇到了一些麻烦。

这是我的代码:

color=['red','green' ,'yellow' , 'blue', 'grey']
gg=random.sample(color, 1)
print(gg)
jj=(farba.index(gg))

我得到了什么:

['green']
ValueError: ['green'] is not in list

谁能帮帮我?

【问题讨论】:

  • 好吧,green 是您列表中的一个元素,而不是索引。所以你不能用它作为索引。

标签: python arrays list valueerror


【解决方案1】:

gg 是一个列表,而不是一个字符串。列表['green'] 不在color 中,而字符串'green' 在。尝试使用random.choice() 而不是sample()

【讨论】:

    【解决方案2】:

    根据python docs

    返回从种群序列或集合中选择的唯一元素的 k 长度列表。用于无放回的随机抽样。

    所以,random.sample 返回一个列表。您可以获取列表的第一项:

    color = ['red','green' ,'yellow' , 'blue', 'grey']
    gg = random.sample(color, 1)[0]
    print(gg)
    jj = farba.index(gg)
    

    或者,使用random.choice

    从非空序列 seq 返回一个随机元素。如果 seq 为空,则引发 IndexError。

    color = ['red','green' ,'yellow' , 'blue', 'grey']
    gg = random.choice(color)
    print(gg)
    jj = farba.index(gg)
    

    注意:我还重新格式化了代码以使其更具可读性。

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2017-09-17
      • 2017-12-29
      • 2022-12-17
      • 2022-01-12
      • 2018-07-05
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多