【问题标题】:How to compare and store the list number into a variable如何比较列表编号并将其存储到变量中
【发布时间】:2021-07-18 00:53:55
【问题描述】:

每次 dataValue 等于数据时,我都会尝试获取列表编号。我想获得将在数据变量的 [] 中显示的数字。这可能吗?

for x in data:
   if dataValue == x:
   #gets the current array number and stores it

【问题讨论】:

  • 通常的用法是for index, x in enumerate(data): - index 是您要查找的号码。
  • 您似乎正在寻找index 方法。请参阅您的列表教程。 my_store = data.index(x).

标签: python arrays list for-loop


【解决方案1】:

您可以使用列表推导来获取索引列表:

indices = [index for index, x in enumerate(data) if x == dataValue]

【讨论】:

    【解决方案2】:

    添加引用计数器将提供您正在寻找的数据。

    例子:

    i = 0
    positions = []
    for x in data:
      if x == dataValue:
        positions.append(i)
      i++
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多