python-3.x “TypeError:无法使用筛选器函数解包不可迭代的int对象”

hof1towb  于 2022-12-20  发布在  Python
关注(0)|答案(2)|浏览(157)

我有一个列表,我想使用filter函数过滤列表中的元组,但是我遇到了一个无法解决的问题。
我的代码:

liste = [(3,4,5),(6,8,10),(3,10,7)]

def ucgen_mi(s):
    for g in s:
        a, b, c = g
        if (a + b > c and a + c > b and c + b > a):
            return True
        else:
            return False

print(list(filter(ucgen_mi, liste)))

追溯:

Traceback (most recent call last):
  File "D:\Python Çalışmalar\Çalışmalar\Gömülü Fonksiyonlar\P2.py", line 30, in <module>
    print(list(filter(ucgen_mi, liste)))
  File "D:\Python Çalışmalar\Çalışmalar\Gömülü Fonksiyonlar\P2.py", line 19, in ucgen_mi
    a, b, c = g
TypeError: cannot unpack non-iterable int object

我也试过这种方法,但结果是一样的。它在这一行给出错误:第一个月

for a,b,c in s:def ucgen_mi(s):
    for a,b,c in s:
        if (a + b > c and a + c > b and c + b > a):
            return True
        else:
            return False

为了测试我编写的算法,我分别尝试了列表中的bundle,发现它们都按照我想要的方式进行了过滤。

liste = [(3,4,5)]

def ucgen_mi(s):
    for g in s:
        a, b, c = g
        if (a + b > c and a + c > b and c + b > a):
            return True
        else:
            return False

print(ucgen_mi(liste))
# result: True

还有:

liste = [(3,10,7)]

def ucgen_mi(s):
    for g in s:
        a, b, c = g
        if (a + b > c and a + c > b and c + b > a):
            return True
        else:
            return False

print(ucgen_mi(liste))
# result: False

我哪里做错了,你能帮帮我吗?

ilmyapht

ilmyapht1#

过滤器隐式循环liste,因此函数一次只需要处理一个元素:

def ucgen_mi(g):
    a, b, c = g
    if (a + b > c and a + c > b and c + b > a):
        return True
    else:
        return False

示例:

print(list(filter(ucgen_mi, [(3, 4, 5), (6, 8, 10), (3, 10, 7)])))

# result: [(3, 4, 5), (6, 8, 10)]

错误消息TypeError: cannot unpack non-iterable int object可以理解为:
filter检查第一个元素(3, 4, 5)是否满足要求时,它被传递给ucgen_mi,因此s等于(3, 4, 5)。(for g in s),而g变成了3,然后你试着解压缩ga, b, c = g),这是没有意义的(=〉"cannot unpack non-iterable int object")。

kqhtkvqz

kqhtkvqz2#

filter函数take,函数或None,可迭代。
下面是filter文档

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.

它从可迭代对象(list/dict/tuple/generator)中获取单个可迭代对象,并对其进行计算,即它与lambda x: x if func(x)有点相同
你需要修改这个函数,使它每次计算每个可迭代对象而不是整个列表。
以下是改进的代码示例

def ucgen_mi(array):
    a, b, c = array
    if (a+b > c) and (a+c > b) and (b+c>a):
            return True
    return False 
liste = [(3,4,5),(6,8,10),(3,10,7)] 
result = list(filter(ucgen_mi, liste))
print(result)
# [(3, 4, 5), (6, 8, 10)]

相关问题