为什么过滤器功能不能pickle?

我想在python中合并两个列表过滤这个获得的列表。


我有以下数据框 df:


+---+--------+

|v1 | v2 | v |

+---+--------+

|  2|   4| 24|

|  4|   2| 42|

|  1|   1| 11|

|  1|   3| 13|

|  2|   2| 22|

+---+----+---+

我有两个广播变量(collectAsMap):


t1: {'3': ['4'], '1': ['2', '4', '3'], '2': ['3', '4']}

t2: {'3': ['4'], '5': ['6'], '1': ['2']}

我尝试了以下操作以过滤和合并列表


merge_udf = udf(merge, ArrayType(StringType()))

df = df.distinct().withColumn('MergeList', merge_udf(df.v1, df.v2)

在哪里:


"""merge two lists in one list"""

def merge2List(listA, listB):

    merge = [(itemA+itemB) for itemA in listA for itemB in listB]

    return merge


"""merge the entry of two entries of dataframes"""

def merge(x, y):

    listA = t1.value.get(x)

    if(listA is None):

        listA = []

        listA.append(x)


    listB = t2.value.get(y)

    if(listB is None):

        listB = []

        listB.append(y)

    m = merge2List(listA, listB)

    return m

得到的结果如下:


+---+---------+------------+

|v1 |v2       |   MergeList|

+---+---------+------------+

|  2|        4|    [34, 44]|

|  4|        2|        [42]|

|  1|        1|[22, 42, 32]|

|  1|        3|[24, 44, 34]|

|  2|        2|    [32, 42]|

+---+---------+------------+

我有一个 t3 广播变量,其中print(list(t3.value.keys()))给出['24', '42', '11', '13', '22']


现在我想过滤掉合并列表列中每个列表中的元素。因此,我创建了以下函数并更新了 merge2List 函数:


def filterList(v):

    vert = list(t3.value.keys())

    if(v in vert):

        return True

    return False



"""merge two lists in one list"""

    def merge2List(listA, listB):

        merge = [(itemA+itemB) for itemA in listA for itemB in listB]

        filteredList = filter(filterList, merge)

        return filteredList

引发以下异常:


_pickle.PicklingError: Can't pickle <function filterList at 0x2b2fb1aa6840>: attribute lookup filterList on __main__ failed

有人可以帮助确定我的错误在哪里吗?


小唯快跑啊
浏览 173回答 3
3回答

元芳怎么了

由于过滤器正在懒惰地评估,泡菜无法读取值。因为它们还不存在。它返回一个迭代器。尝试:filtered = filter(m_func, m_list)pickle.dumps(list(filtered))

弑天下

尝试:pickle.loads(pickle.dumps(list(filteredList)))

慕莱坞森

以上两个答案都是正确的。但我按照以下方法解决问题:def&nbsp;merge2List(listA,&nbsp;listB): &nbsp;&nbsp;&nbsp;&nbsp;merge&nbsp;=&nbsp;[(itemA+itemB)&nbsp;for&nbsp;itemA&nbsp;in&nbsp;listA&nbsp;for&nbsp;itemB&nbsp;in&nbsp;listB] &nbsp;&nbsp;&nbsp;&nbsp;filteredList&nbsp;=&nbsp;filter(lambda&nbsp;x:&nbsp;x&nbsp;in&nbsp;list(t3.value.keys()),&nbsp;merge) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;list(filteredList)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python