Python:返回值太多,无法解包

问题描述 投票:-1回答:1

我希望这不是重复的。我知道要解压缩的值太多了。我返回两个值,并尝试接受两个值。

我只提供一小部分代码,希望就足够了。

def test(all the arguments in function_parameters):
    // do something


    dfData.append([fileToCheck,5,";".join(faceNames),frameTime,";".join(faceDistances),";".join(faceLocations),";".join(gender),str(";".join(age)),str(";".join(expression))])

    if len(face_locations) != 0:
        keyPointsData.append([fileToCheck,time,str(";".join(encodings)),str(";".join(encodings)),time])
    else:
        keyPointsData.append([fileToCheck,time,"","",time])

    return dfData, keyPointsData

#Start multiprocessing
#Pass variables to the function
function_parameters = zip(
    images_to_check,
    itertools.repeat(known_names),
    itertools.repeat(known_face_encodings),
    itertools.repeat(tolerance),
    itertools.repeat(processImages),
    itertools.repeat(processVideos),
    itertools.repeat(fpstoprocess),
    itertools.repeat(upsample),
    itertools.repeat(algo),
    itertools.repeat(onlydetection),
    itertools.repeat(saveimagespath),
    itertools.repeat(savefullimages),
    itertools.repeat(savefaceimage),
    itertools.repeat(enablebox),
    itertools.repeat(maxarea),
    listNumber,
    itertools.repeat(totalImages),
    itertools.repeat(imageExtensions),
    itertools.repeat(videoExtensions),
    itertools.repeat(debug),
    itertools.repeat(age),
    itertools.repeat(gender),
    itertools.repeat(expression),
    itertools.repeat(keypointsDF)
)



rows,keypointsData =  pool.starmap(test, function_parameters)

tdfDatakeyPointsData是多维列表。我正在使用多线程

我在此行rows,keypointsData = pool.starmap(test, function_parameters)出现错误

完整错误消息

 Traceback (most recent call last):

  File "face.py", line 829, in <module>
    main()
  File "face.py", line 702, in main
    process_images_in_process_pool()
  File "face.py", line 584, in process_images_in_process_pool
    rows,keypointsData =  pool.starmap(test, function_parameters)
ValueError: too many values to unpack (expected 2)
python
1个回答
1
投票

根据官方文档https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap

starmap使用一个迭代器以与迭代器不同的输入来调用该函数,然后返回另一个带有所有输出及其相应输入的迭代器。

所以这里举个例子:

def test(a, b):
    return a, b

现在使用不同输入的迭代器调用函数:

iter1 = zip([1, 2], [3, 4])
list_of_results = pool.starmap(test, iter1)

>>> list_of_results
>>> [(2, 3), (4, 5)]
x, y = pool.starmap(test, iter1) # unpacking will work

但是如果迭代器调用的次数超过2,则使用2个变量进行解压缩将失败:

iter2 = zip([1, 2, 3], [4, 5, 6])
list_of_results = pool.starmap(test, iter2)
>>> list_of_results
>>> [(2, 5), (3, 6), (4, 7)]
x, y = pool.starmap(test, iter1) # unpacking will fail

因此,首先将结果存储在list_of_results中,然后对其进行迭代以使用输出值,以避免出现拆包问题。

希望它将清除疑问和问题

© www.soinside.com 2019 - 2024. All rights reserved.