【问题标题】:How to iterate over full list in python? For loop stops at 1st instance如何遍历python中的完整列表? For 循环在第一个实例处停止
【发布时间】:2019-09-22 01:57:09
【问题描述】:

我一直在尝试让我的 for 循环遍历名为 pdg_vals 的列表的完整值。我想获取所有 14 值的索引号。然后我想使用这些索引值创建一个新列表。

Python 不断返回该规定的第一个实例。也就是说,它表明我正在附加的新列表 (pdg_ent) 仅填充了 pdg_vals 值为 14 的第一个实例的索引值。

我尝试使用 += 操作进行追加。

代码如下:

myfile = ROOT.TFile("/home/hilary/root/compile/Research/GENIE_atm.root")
mydir = myfile.GENIE
mytree = mydir.Get("Event")
pdg_vals = [] #an empyt list to fill pdg values
for e in mytree:
    for v in e.mc_pdg:
        pdg_vals += [v] #fill empty list with mc_pdg values
#pdg_vals
pdg_ent = []

for x in pdg_vals:
    if x == 14:
        pdg_ent += [pdg_vals.index(x)]

pdg_ent

pdg_vals 列表如下所示:

[12,
 1000180400,
 2112,
 1000180390,
 11,
 2212,
 2212,
 2000000002,
 2000000101,
 14,
 1000180400,
 2212,
 1000170390,
 14,
 2214,
 2212,
 111,
 2212,
 111,
 2212,
 2000000002,
 12,
 ...]

显然,如果我正确编写代码,我的新 pdg_ent 列表中的第一个值应该是 9,第二个应该是 13 等等......

这是 pdg_ent 的输出

[9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 9,
 ...]

为什么 python 在新列表中只添加旧列表中值 14 的第一个实例?

【问题讨论】:

    标签: python-3.x list indexing


    【解决方案1】:

    'index'函数不是你想要的

    pdg_vals.index(x) 将如documentation 所述,“返回值等于x 的第一个 项的列表中从零开始的索引” - 在您的情况下当 x 为 14 时为 9。因此,如果您不希望返回第一个值,那不是您需要的。

    枚举

    枚举函数 (https://docs.python.org/3/tutorial/datastructures.html#looping-techniques) 似乎正是您所需要的:

    for index, value in enumerate(list):
      if value == 14:
         print(index)
    

    【讨论】:

      【解决方案2】:
      i = 0
      for x in pdg_vals :
          if x == 14 :
              print(i)
          i += 1
      

      这将适用于您的特定场景。但是,如果您需要按升序排序,则使用二分搜索会更快。

      【讨论】:

        猜你喜欢
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2022-01-06
        • 2021-10-25
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        相关资源
        最近更新 更多