【问题标题】:Perform a list comprehension inside of a for loop in Python [closed]在 Python 中的 for 循环内执行列表理解[关闭]
【发布时间】:2021-04-15 23:43:40
【问题描述】:

简而言之,我需要从该集合中获取每个元素 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])

【问题讨论】:

  • 为什么在这里使用列表理解是一个约束?这没有任何意义。
  • “它不工作”不是一个有效的问题陈述。
  • 好的,@MadPhysicist...我得到以下结果[] [] ['dusthaze-sky']
  • 当您的集合是三个未定义的变量时,您如何期望得到 anything -- 您存储的文件名是具有相同视觉值的字符串。
  • mountain_004 不在您的文件集中时,您希望如何获得输出?

标签: python list for-loop if-statement list-comprehension


【解决方案1】:

你不需要枚举:

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

【讨论】:

    【解决方案2】:

    列表推导用于表达映射/过滤操作以从任意迭代创建列表。您在此处描述的是规范的 grouping 操作。所以使用基于 dict 的分组习语:

    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),这是多项式时间,但基于 dict 的分组习语是线性时间,O(N) on the length of arr

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多