无法修改二维选项卡

2024-07-02 13:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图修改2D选项卡,但python显示以下错误:

tab[Lig][Col]=汽车

TypeError:“str”对象不支持项分配

tab = input().split(' ')
nbLignes = int(tab[0])
nbColonnes = int(tab[1])
nbRectangles = int(input())
tableau = [["."] * nbColonnes for m in range(nbLignes)]

for k in range(nbRectangles):
   tab2 = input().split(' ')
   iLig1=int(tab2[0])
   iLig2=int(tab2[2])
   iCol1=int(tab2[1])
   iCol2=int(tab2[3])
   car=tab2[4]
   caractere = tab2[4]
   for Lig in range(iLig1,iLig2+1):
      for Col in range(iCol1,iCol2+1):
         tab[Lig][Col] = car
for Lig in range (nbLignes):
   for Col in range(nbColonnes):
      print(tab[Lig][Col],sep= ' ')

Tags: inforinputrangecoltabintsplit
1条回答
网友
1楼 · 发布于 2024-07-02 13:31:26

查看您的代码:

tab = input().split(' ')

这告诉我tabstrlist

In [1]: tab = input().split(' ')                                                        
Hello there. How are you?
Out[1]: ['Hello', 'there.', 'How', 'are', 'you?']

所以当你说tab[Lig][Col] = car时,你是在试图改变字符串中的一个字母。在Python中,字符串是不可变的。因此出现了错误:

In [2]: test = 'foo'                                                                                     
Out[2]: 'foo'

In [3]: test[1]                                                                                          
Out[3]: 'o'

In [4]: test[0]                                                                                          
Out[4]: 'f'

In [5]: test[2] = 'b'                                                                                    
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-5-b8fb07018fbc> in <module>
  > 1 test[2] = 'b'

TypeError: 'str' object does not support item assignment

相关问题 更多 >