python - 列表理解中有多少逻辑?

标签 python list-comprehension

我的代码中有一个列表理解,看起来像这样:

dataPointList = [
     map(str, 
        [ elem for elem in dataFrame[column] 
           if not pd.isnull(elem) and '=' in elem
        ]
     ) for column in list(dataFrame)
]

我想知道,何时分解列表理解是否有一般的经验法则?列表推导式中的逻辑是否过多?

最佳答案

您可能不想混合使用 map 和列表理解,尤其是当根本不需要 map 时:

>>> list(map(str, [x for x in [1, 2, 3]]))
['1', '2', '3']
>>> [str(x) for x in [1, 2, 3]]
['1', '2', '3']

这意味着您可以直接在列表理解中简单地应用 str[elem]:

dataPointList = [
    [ str(elem) for elem in dataFrame[column]
       if not pd.isnull(elem) and '=' in elem
    ] for column in list(dataFrame)
]

然后,DataFrame 就已经是可迭代的了。无需将其转换为列表:

>>> [x for x in list(pd.DataFrame(d))]
['one', 'two']
>>> [x for x in pd.DataFrame(d)]
['one', 'two']

你的代码变成:

dataPointList = [
    [ str(elem) for elem in dataFrame[column]
       if not pd.isnull(elem) and '=' in elem
    ] for column in dataFrame
]

请注意,由于您需要嵌套列表,因此不能使用双列表推导式:

>>> [(a,b) for a in x for b in y]
[(1, 3), (1, 4), (2, 3), (2, 4)]
>>> [[(a,b) for b in y] for a in x]
[[(1, 3), (1, 4)], [(2, 3), (2, 4)]]

关于python - 列表理解中有多少逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262904/

相关文章:

python - 如何使用字符串变量中的列表名称

python - 如果嵌套列表中不存在元素,如何有效地检查和添加?

python - python中的时间和日期时间差异触发错误

python - 在 Google App Engine 项目上构建 Sphinx Autodoc

python - 在背景图像上叠加散点图并更改轴范围

Python 列表理解太慢

python - 在其他列表项中查找列表项的列表索引

python - 如何从现有字典中有选择地创建字典?

python - sklearn 指标分类_报告版本输出

python - list() 使用的内存比列表推导略多