簡體   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