【问题标题】:Returning index of true value返回真值索引
【发布时间】:2019-07-12 01:37:47
【问题描述】:

对于下面编写的代码,我想打印samples_avg 中的值索引,它在maxlist 中为samples_avg 中的每个列表返回true。所以对于列表

samples_avg = [[1, 12, 3], [15000, 4, 3], [1, 144, 45]]

我希望返回值类似于

filtered = [[], [0], [1, 2]]

因为在第一个列表中没有条件为真的索引,所以第二个列表的索引 0 为真,samples_avg 内最后一个列表的索引 1 和 2 为真

samples_avg = [[1, 12, 3], [15000, 4, 3], [1, 144, 45]]
def check(samples_avg):
    filtered = []
    maxval = [max(x) for x in zip(*samples_avg)]
    maxlist = ([r >= (m/5) for row in samples_avg for r, m in zip(row, maxval)])

    results =[[] for i in samples_avg]
    for i in results:
        filtered.append([x for x, y in zip(samples_avg[i], maxlist) if y == True])
        print (np.where((filtered) is True))

这当前返回三个空数组。我该如何解决这个问题,以便数组包含索引?任何建议将不胜感激!

【问题讨论】:

  • 我实际上对m/5 的东西感到困惑,但 nvm。使用enumerate 就像来自@Adam.Er8 的答案

标签: python loops numpy


【解决方案1】:

只是稍微修改了您的列表理解,使用 enumerate 来获取实际索引,并在 if 子句中使用条件为 true 而不是 map 值。

试试这个:

samples_avg = [[1, 12, 3], [15000, 4, 3], [1, 144, 45]]
def check(samples_avg):
    maxval = [max(x) for x in zip(*samples_avg)]
    return [[i for i,(r, m) in enumerate(zip(row, maxval)) if r >= (m/5)] for row in samples_avg]

print(check(samples_avg))

输出:

[[], [0], [1, 2]]

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 2021-12-17
    • 2010-10-10
    • 2019-01-11
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多