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

Perform a list comprehension inside of a for loop in Python

简而言之,我需要从这个集合中获取每个元素 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', 5, 5, 252, 119], 
           ['opencountry_test_017', 'yellow-field', 4, 140, 254, 250],
           ['mountain_004', 'blue-sky', 9, 5, 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])

列表理解用于表达 mapping/filtering 操作以从任意可迭代对象创建列表。您在这里描述的是规范的 grouping 操作。所以使用基于字典的分组习惯用法:

arr = [['volcano_021', 'dusthaze-sky', 5, 1, 251, 55], 
           ['volcano_021', 'rocky-mountain', 11, 75, 249, 256],
           ['opencountry_test_017', 'overcast-sky', 5, 5, 252, 119], 
           ['opencountry_test_017', 'yellow-field', 4, 140, 254, 250],
           ['mountain_004', 'blue-sky', 9, 5, 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', 'rocky-mountain'], ['overcast-sky', 'yellow-field']]

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

的长度上