首页 > 解决方案 > 为什么函数 1 不调用 fun2

问题描述

为什么功能不起作用?

def fun2(a,b):
    a.sort(key = lambda item: ([str,int].index(type(item)), item))
    print(a[b-1],a[b-2])

def filter(x,y):
    list2=[]
    q=200
    while x!=200:
        if  y[x]%1 ==0 :
            list2.append(y[x])
            x=x+1
    fun2(list2,q)
list1=[]
a=0
b=0
c=0.5
d=65
z=0
while a!=100:
    list1.append(a)
    a=a+1
while b!=50:
    list1.append(c)
    b=b+1
    c=c+0.43
while d!=115:
    list1.append(chr(d))
    d=d+1
q=len(list1)
print(list1)
print(filter(z,list1))

为什么过滤器不调用函数2?为什么我在这里犯错误?我想从 list2 中打印 2 个最大整数

标签: python-3.x

解决方案


你在这里有一个无限循环:

while x != 200:
    if  y[x]%1 == 0 :
        list2.append(y[x])
        x = x + 1

只要y[x]不是整数,条件就不是真,并且x不再增加。

你可能想做:

while x <= 200:
    if y[x] == int(y[x]):
        list2.append(y[x])
    x += 1

更新:哦,我看到你的列表中也有非数字项目......另外,你不应该使用while循环来迭代列表。这是一个更好的方法

for item in y:
    try:
        if item == int(item):
            list2.append(item)
    except ValueError:
        pass

推荐阅读