【问题标题】:int object is not subscriptable while indexing索引时 int 对象不可下标
【发布时间】:2019-02-14 05:19:13
【问题描述】:

我只是想编写一个简单的代码来找出具有最大相似元素数量的字符串,但是在将字符串的各个元素与目标字符串进行比较时,我得到了错误 int object is not subscriptable。编辑:错误在行中:如果 a[b]==t[b]: please help 。在代码中,我获取了一个字符串列表,然后将其与目标字符串字母表进行比较,并打印具有最多相似字母表(具有相同索引号)的字符串

n=int(input('enter the number of elements in the list'))
t=input('enter the target string')
l=[]
for x in range(0,n):
    st=input('enter the string')
    l.append (st)
length=len(t)
high=0
for a in l:
    score=0
    for b in range(0,length):
        if a[b]==t[b]:
            score+=1
    if score>high:
        high=score
        word=a
print('the word with the maximum score is :',word)

【问题讨论】:

  • a 不是一个列表,而是一个值。 a[b] 不起作用,应该只是 a
  • 您能否更具体地了解该错误,例如它在哪一行?你的目标是什么,你尝试过什么?见this link
  • 你能把大写去掉吗?
  • 他是否在某个时候更改了代码,我可以发誓他附加了 x
  • 您可以通过学习一些降价语法来美化您的文章/答案/问题。您可能会发现 stackedit.io 有点帮助。

标签: python python-3.x list int


【解决方案1】:

将整数附加到 l

for x in range(0,n):
    st=input('enter the string')
    l.append (x) #here

然后你循环 l

for a in l:
    score=0
    for b in range(0,length):
        if a[b]==t[b]:  <--------- #here you say the b'th value of the integer a

整数不是数组,它只有一个值

【讨论】:

    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2021-11-26
    • 2012-02-21
    • 2018-08-07
    • 2015-04-26
    相关资源
    最近更新 更多