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

时间:2018-03-28 09:24:50

标签: python list-comprehension palindrome

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

以下是问题:

我正在尝试使用过滤器(is_palindrome,范围(1,1000))生成像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]

我想知道为什么以及如何让它成为[1,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))))

P.S。我知道有一种更简单的方法,比如返回str(n)== str(n)[:: 1],但我只是想尝试另一种方法:)

1 个答案:

答案 0 :(得分:1)

那么如何跟踪您的错误,试试这个:

只需打印一个打印,然后在索引错误中查看功能失败的地方:

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]