简体   繁体   English

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

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

How to Filter the palindrome numbers in the given tuple and save it in the tuple?如何过滤给定元组中的回文数并将其保存在元组中?

My code:我的代码:

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

Convert your integer to a string.将您的 integer 转换为字符串。 Also, you weren't using the inverse slicing of the string correctly此外,您没有正确使用字符串的反向切片

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

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

Output: Output:

11
22
101
111

You also mention that you want to save the result in a tuple.您还提到要将结果保存在元组中。 Use a generator expression for that:为此使用生成器表达式

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

Output: Output:

(11, 22, 101, 111)

You cannot use indices for integer values.您不能对 integer 值使用索引。

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

Also str(i)[:] is the same thing with str(i) and str(i)[-1:] only takes the last digit of the number. str(i)[:]也与str(i)相同,而str(i)[-1:]只取数字的最后一位。

If you want to get the number reversed you have to use str(i)[::-1] .如果要反转数字,则必须使用str(i)[::-1]

This should work just fine:这应该可以正常工作:

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

Check this for a better understanding of the slicing operator:检查以更好地理解切片运算符:

Try This Code:试试这个代码:

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