繁体   English   中英

#如何过滤给定元组中的回文数并将其保存在元组中

[英]#How to Filter the palindrome numbers in the given tuple and save it in the tuple

如何过滤给定元组中的回文数并将其保存在元组中?

我的代码:

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if i[:]==i[-1:]:
        print(i)

Error : TypeError                                 Traceback (most recent call last)
<ipython-input-143-b2b3cfdef377> in <module>
      7 
      8 for i in w:
----> 9     if i[:]==i[-1:]:
     10         print(i)

TypeError: 'int' object is not subscriptable

将您的 integer 转换为字符串。 此外,您没有正确使用字符串的反向切片

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if str(i) == str(i)[::-1]:
        print(i)

Output:

11
22
101
111

您还提到要将结果保存在元组中。 为此使用生成器表达式

tuple(i for i in w if str(i) == str(i)[::-1])

Output:

(11, 22, 101, 111)

您不能对 integer 值使用索引。

  1. i[:]不起作用
  2. str(i)[:]有效。

str(i)[:]也与str(i)相同,而str(i)[-1:]只取数字的最后一位。

如果要反转数字,则必须使用str(i)[::-1]

这应该可以正常工作:

w = tuple(i for i in w if str(i) == str(i)[::-1])
print(w)

检查以更好地理解切片运算符:

试试这个代码:

w = (10,11,12,21,22,101,123,111,152)
for i in w:
    if str(i)[:]==str(i)[::-1]: 
        print(i)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM