在 Python 的 for 循环内执行列表理解

问题描述

简而言之,我需要的是从这个集合中获取每个元素 uniqueFiles = {volcano_021,opencountry_test_017,opencountry_test_017} 从每个嵌套数组中获取索引 1 的元素,其中索引 0 等于将要迭代的 uniqueFiles 集合的元素。

例如考虑以下列表:

    arr = [['volcano_021','dusthaze-sky',5,1,251,55],['volcano_021','rocky-mountain',11,75,249,256],['opencountry_test_017','overcast-sky',252,119],'yellow-field',4,140,254,250],['mountain_004','blue-sky',9,246,82]]

我试图做的是通过 for 循环为这样的循环获得以下结果

'volcano_021' => ['dusthaze-sky','rocky-mountain']
'opencountry_test_017'=> ['overcast-sky','yellow-field']
'mountain_004' => ['blue-sky']

我想出了以下代码......但是它不起作用。

我想使用列表理解来做到这一点

  for file in uniqueFiles:
    print([n[1] for i,n in enumerate(arr) if n[i] == file])

解决方法

你不需要枚举:

for file in uniqueFiles:
    print([n[1] for n in arr if n[0] == file])
,

列表推导式用于表达映射/过滤操作,以从任意可迭代对象创建列表。您在这里描述的是规范的分组操作。所以使用基于 dict 的分组习惯用法:

arr = [['volcano_021','dusthaze-sky',5,1,251,55],['volcano_021','rocky-mountain',11,75,249,256],['opencountry_test_017','overcast-sky',252,119],'yellow-field',4,140,254,250],['mountain_004','blue-sky',9,246,82]]
uniqueFiles = {'volcano_021','opencountry_test_017','opencountry_test_017'}

grouper = {}
for first,second,*_ in arr:
    if first in uniqueFiles:
        grouper.setdefault(first,[]).append(second)

这会给你这样的结果:

>>> grouper
{'volcano_021': ['dusthaze-sky','rocky-mountain'],'opencountry_test_017': ['overcast-sky','yellow-field']}

您可以使用如下算法:

>>> [[y for x,y,*_ in arr if x == target] for target in uniqueFiles]
[['dusthaze-sky',['overcast-sky','yellow-field']]

但请注意,这需要多次遍历 arr,使得上述算法在 arruniqueList 的大小上为 O(N*M),这是多项式时间,但是基于字典的分组习语是线性时间,在 arr

的长度上为 O(N)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...