回数是指从左向右读和从右向左读都是一样的数, 请利用filter()筛选出回数
时间: 2023-06-15 12:05:02 浏览: 137
利用Filter()实现回数功能
可以将数字转化为字符串,然后判断字符串是否为回文字符串来筛选回数。以下是示例代码:
```
def is_palindrome(n):
"""
判断一个数字是否为回数
"""
s = str(n)
return s == s[::-1]
nums = range(1, 1000)
palindromes = filter(is_palindrome, nums)
print(list(palindromes))
```
输出结果:
```
[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]
```
阅读全文