在列表理解中有多少逻辑?

时间:2017-09-17 10:12:36

标签: 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)
]

我在想,是否有一个一般的经验法则,什么时候打破列表理解?你能在列表理解中有太多的逻辑吗?

1 个答案:

答案 0 :(得分:1)

您可能不想混淆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)]]