python - 使这个简单的 for/if block 更像 pythonic

标签 python

我需要将 3 个列表中超过给定最大限制的那些值的索引存储在列表中。这是我得到的:

# Data lists.
a = [3,4,5,12,6,8,78,5,6]
b = [6,4,1,2,8,784,43,6,2]
c = [8,4,32,6,1,7,2,9,23]

# Maximum limit.
max_limit = 20.

# Store indexes in list.
indexes = []
for i, a_elem in enumerate(a):
    if a_elem > max_limit or b[i] > max_limit or c[i] > max_limit:
        indexes.append(i)

这行得通,但我觉得它很丑。我怎样才能让它更优雅/pythonic?

最佳答案

您可以将 for 循环替换为:

indexes = []
for i, triplet in enumerate(zip(a, b, c)):
    if any(e > max_limit for e in triplet):
        indexes.append(i)

...然后您可以将其简化为列表理解:

indexes = [i for i, t in enumerate(zip(a, b, c)) if any(e > max_limit for e in t)]

...虽然这对我来说似乎有点笨拙 - 这确实与个人品味有关,但我更喜欢保持 listcomps 简单;在我看来,三行 for 循环更清晰。

正如 user2357112 所指出的,您可以使用 max() 降低列表理解的表面复杂性:

indexes = [i for i, t in enumerate(zip(a, b, c)) if max(t) > max_limit]

...虽然这不会像 any() 版本(和您自己的代码)那样短路,但可能会稍微慢一些。

关于python - 使这个简单的 for/if block 更像 pythonic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23706447/

相关文章:

python - Pickle跨平台__dict__属性错误

python - 什么时候以及为什么类型对象比字典更好?

python - Cython 的计算不正确

python - 在 Python 中优化集合理解

Python:如何在 python 使用日志记录模块中创建和使用自定义记录器?

python - 如何从目录中找到与输入图像相似的图像?

python - 列表列表中项目的频率

python - 带有int参数的Django HttpResponseRedirect

python - 在 python 中转置/旋转矩阵 block

python - 根据名称作为列表中的字符串调用函数