【问题标题】:Break out of loop if data in one array exceedes some VALUE in another Python如果一个数组中的数据超过另一个 Python 中的某个值,则跳出循环
【发布时间】:2015-08-18 02:17:50
【问题描述】:

我有两个数组,idx,其中id 是一个唯一标识符,它告诉我们x 中的值属于特定组。我想要做的是检查x 中的值以查看是否满足某些条件,如果满足则打印相应的x 值。例如

id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])


  counter = 1
  for i in range(len(id)):
    if id[i] == counter:
        for j in range(i,len(id)):   
           if x[j] > 7:
             continue 
           else:
              print(id[i],x[j])  
              counter += 1    
              break

打印

1 6
2 7
3 5
4 4
5 6

现在如果我们有

id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,11,10,9,8,4,6,2,1])

输出是

1 6
2 7
3 4
4 4
5 6

这不是我想要的输出,因为4 不在id 值为3 的组中。所以我的问题是,如果x 值对应于代表它的id 值而不跳过该组,如何仅评估条件if x[j] > 7:

【问题讨论】:

    标签: python arrays if-statement for-loop conditional-statements


    【解决方案1】:

    我有点困惑,但我会采取行动...... 字典有帮助吗?

    id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
    x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])
    
    dict = {}
    for i in range(len(id)):
        if id[i] not in dict:
            dict[id[i]] = []
        dict[id[i]].append(x[i])
    
    #you now have a dict that is keyed by your group-id and has a list of values for that group.
    
    for group in dict:
        vals_in_group = dict[group]
        for val in vals_in_group:
            #check value? or just print
            print group, val
    

    【讨论】:

    • 因为我以前从未使用过字典,我如何将它整合到我的示例中?会不会像 if val in vals_in_group do something 这样简单?
    • 我把#check 值放在哪里,val 是 vals_in_group 中的元素之一。如果您想检查组列表中是否有某个值,那么是的,您的“if val in val_in_group:”可以工作......在这种情况下,您可能会删除 for 循环(对于vals_in_group 中的 vals) 和 'val' 将是您选择的值。
    • 我对@9​​87654324@ 到底是什么以及如何将dictionary 集成到我的代码中感到有些困惑。您介意为我多解释一下您的代码吗?
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2010-09-27
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多