为什么列表推导生成的列表是空的

2024-04-20 07:37:56 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,对不起,我的英语和布局不好。我在中国是一个Python初学者,这是我用英语问的第一个问题。你知道吗

问题是:

我试图使用filter(is_palindrome,range(11000))生成像121这样的回文数。与这个问题密切相关的代码是is_palindrome(n)函数中的l=[int(i)for i in str(n)]。调试器显示当n=11时,l=[]而不是[1,1],然后IndexError: list index out of range发生在if l[0] != l[-1]。你知道吗

我想知道为什么以及如何让它成为现实。你知道吗

源代码:

def is_palindrome(n):
    p = True
    l = [int(i) for i in str(n)]
    while len(l) != 1:
        if l[0] != l[-1]:
            p = False
            break
        l.pop(0)
        l.pop(-1)
    return p
print(list(filter(is_palindrome, range(1, 1000))))

另外,我知道有一种更简单的方法,比如return str(n)==str(n)[:::1],但我只想试试另一种:)


Tags: 代码inforreturnifisrange布局
1条回答
网友
1楼 · 发布于 2024-04-20 07:37:56

因此,如何跟踪错误,请尝试以下方法:

只需打印一下,看看函数在索引错误时失败的地方:

def is_palindrome(n):
    p = True
    l = [int(i) for i in str(n)]
    while len(l) != 1:
        print("l",l)
        if l[0] != l[-1]:
            p = False
            break
        l.pop(0)
        l.pop(-1)
    return p
print(list(filter(is_palindrome, range(1, 1000))))

输出:

l [1, 0]
    if l[0] != l[-1]:
l [1, 1]
IndexError: list index out of range
l []

您可以清楚地看到,当l为[](空)时,它会给出错误,现在让我们修复它并运行代码

以下是经过一些修改后的函数:

def is_palindrome(n):
    p = True
    l = [int(i) for i in str(n)]

    while len(l) != 1 and l!=[]:
        if l[0] != l[-1]:
            p = False
            break
        l.pop(0)
        l.pop(-1)
    return p
print(list(filter(is_palindrome, range(1, 1000))))

输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]

相关问题 更多 >