number palindrome TypeError:“ int”对象不可下标

时间:2020-06-20 01:14:35

标签: python numbers

我想用数字列表创建一个新列表,并且在新列表中只能有回文数。

l = [34, 435, 343, 765, 87878, 25752]


nwelist = [343, 87878, 25752]

我尝试过的事情:

d = []
l = [34, 435, 343, 765, 87878, 25752]
for i in l:
    if str(i)[0:len(l)//2] == i[len(l)//2:-1]:
        d.append(i)

错误:

Traceback (most recent call last):
  File "C:/Users/Caitlin/AppData/Local/Programs/Python/Python38-32/continue.py", line 4, in <module>
if str(i)[0:len(l)//2] == i[len(l)//2:-1]:
TypeError: 'int' object is not subscriptable

3 个答案:

答案 0 :(得分:3)

检查

d = [x for x in l if str(x)==str(x)[::-1]]
[343, 87878, 25752]

答案 1 :(得分:1)

给您一个错误的问题是,在==的右侧,您有i[len(l)//2:-1],应在str(i)[len(l)//2:-1]处。但是,还有其他问题。由于您需要将i用作字符串,因此建议您先对其进行转换,并预先计算其长度。然后,您可以简化回文检查代码:

d = []
l = [34, 435, 343, 765, 87878, 25752]
for i in l:
    s = str(i)
    ln = len(s)
    if s[0:ln//2] == s[ln-1:ln//2:-1]:
        d.append(i)

print(d)

输出:

[343, 87878, 25752]

请注意,这可以修复代码中的错误,但是我绝对建议使用@YOBEN_S答案中的代码。

答案 2 :(得分:0)

您也可以只使用df %>% unite(St_Lat_Long, Start_Latitude, Start_Longitude, sep = ',') %>% unite(End_Lat_Long, End_Latitude, End_Longitude, sep = ',') %>% group_by(St_Lat_Long, End_Lat_Long) %>% mutate(ID = cur_group_id()) 并创建条件:

filter
my_list = [34, 435, 343, 765, 87878, 25752]

[*filter(lambda x: str(x) == str(x)[::-1], my_list)]