如何在一个已经在python中保存整数值的索引处将字符分配给字符串?

问题描述 投票:0回答:1

这是代码,我收到错误:

a[i] = a[i][:j] + 'X' + a[i][j+1:]

我想要更改字符串的值

n = int(input())
a = [0 for i in range(n)]

for i in range(n):
    a[i] = input()

for i in range(n):
    if i == 0 or i == (n-1):
        print(a[i])
    else:

        for j in range(1, n-1):
            if (int(a[i][j-1] < int(a[i][j]) and int(a[i][j+1]) < int(a[i][j]) and int(a[i-1][j]) < int(a[i][j]) and int(a[i+1][j]) < int(a[i][j])):
                a[i] = a[i][:j] + 'X' + a[i][j+1:]
        print(a[i])

INPUT:

4
1112
1912
1892
1234

预期产量:

1112
1X12
18X2
1234

但得到错误:

Traceback (most recent call last):
  File "CavityMap.py", line 10, in <module>
    if(int(a[i][j-1])<int(a[i][j]) and int(a[i][j+1])<int(a[i][j]) and int(a[i-1][j])<int(a[i][j]) and int(a[i+1][j])<int(a[i][j])):
Value Error: invalid literal for int() with base 10: 'X'
python string python-3.x int
1个回答
1
投票

问题是,基于你的例子,一旦你在第三行

1112
1912
1892 <- When you are finally here
1234

第二行已经是1X12。所以,a[]现在看起来像

1112
1X12 # Take note of the 'X' here.
1892
1234

所以,当你达到条件陈述的...and int(a[i-1][j]) < int(a[i][j]) and...部分时,a[i-1][j]将返回'X'。现在,由于'X'是一个文字(字母字符),因此不能使用int()将类型转换为整数。您需要使用ord()将字符转换为其代表性整数(即ord('a')返回97),但这不会给出正确的结果。


从我的头脑中解决这个问题的一个解决方案是使用两个数组。第一个数组(我们称之为数组A)将包含用户输入的所有值,不会被修改。数组A将用于比较每个元素中的字符。第二个数组(数组B)将用于包含修改后的值。换句话说,数组B将具有Xs的值。代码看起来与您的初始代码类似,但只需进行一些更改即可包含其他数组。

n = int(input())
a = [0 for i in range(n)]  # This array will not be modified nor printed. This
                           # will be used for comparisons only.
b = [0 for i in range(n)]  # This array will be used to store the modified values and
                           # be the one printed instead.

for i in range(n):
    a[i] = input()
    b[i] = a[i]  # Here, we're duplicating the values from a[] to b[].

for i in range(n):
    if i == 0 or i == (n - 1):
        print(a[i])
    else:
        for j in range(1, n - 1):
            if (int(a[i][j - 1]) < int(a[i][j])
                and int(a[i][j + 1]) < int(a[i][j])
                and int(a[i - 1][j]) < int(a[i][j])
                and int(a[i + 1][j]) < int(a[i][j])):
                b[i] = a[i][:j] + 'X' + a[i][j + 1:]
        print(b[i])
© www.soinside.com 2019 - 2024. All rights reserved.