繁体   English   中英

遍历列表中的列表

[英]Iterating over lists within a list

我已经写了一些代码来遍历列表列表,这些列表根据i在列表中的索引是否大于其他列表中相同索引处的所有其他值j来返回true或false:

for i in range(len(list)):
    for j in range(0, len(list)):
        if (np.any(list[i]) >= np.all(list[j])):
            count = count + 1
            results.append((count == len(list) - 1))

print (results)

这样可以很好地找到正确的答案。 但是,问题在于该函数不会像我希望的那样遍历列表中的整个列表。 例如,从这样的列表中:

list =[[1, 3, 6, 5, 9], [7, 2, 8, 9, 1]]

我期望这样的输出:

results = [False, True, True, False, False, True, False, True, True, False]

但是,它仅迭代前两个索引和停止。

results = [False, True, True, False]

我知道这可能是因为list的长度为2,但是我没有一个很好的解决方案来使函数迭代列表中的整个列表。 任何帮助将不胜感激!

尽量避免使用Python关键字作为变量名(例如: list )。 但是,如果您在循环之前计算每列的最大值,则可以更轻松地计算出类似的结果:

码:

lst = [[1, 3, 6, 5, 9], [7, 2, 8, 9, 1]]
maxes = [max(x) for x in zip(*lst)]
print([r == m for row in lst for r, m in zip(row, maxes)]

或作为一个标准for循环:

result = []
for row in lst:
    for r, m in zip(row, maxes):
        result.append(r == m)

结果:

[False, True, False, False, True, True, False, True, True, False]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM