相关疑难解决方法(0)

迭代Python 3中的数组

我没有编写一段时间并尝试重新使用Python.我正在尝试编写一个简单的程序,通过将每个数组元素值添加到一个总和来对数组求和.这就是我所拥有的:

def sumAnArray(ar):
    theSum = 0
    for i in ar:
        theSum = theSum + ar[i]
    print(theSum)
    return theSum
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

line 13, theSum = theSum + ar[i]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

我发现我正在尝试做的事情显然就像这样简单:

sum(ar)
Run Code Online (Sandbox Code Playgroud)

但显然我并没有正确地遍历数组,我认为这是我需要为其他目的正确学习的东西.谢谢!

python arrays sum python-3.x

12
推荐指数
2
解决办法
4万
查看次数

TypeError:list indices必须是整数,而不是list.怎么修?

其中包含TypeError的代码."列表索引必须是整数,而不是列表",尽管它们是整数.我很感激你帮助我弄清楚什么是错的.我需要的是从源7x5选项卡获取具有不同值的矩阵7x5.错误发生在最后一行.

lines = []

with open("text.txt") as f:
    for line in f:
        line = [int(x) for x in line if (x != ' ') and (x != '\n')]
        lines.append(line)
    f.close()
Run Code Online (Sandbox Code Playgroud)

读取文件后的内容是带有"行"数字的列表列表.这是整数.不是字符串.喜欢:

>> [[1, 2, 3...], [4, 5, 6...], [7, 8, 9...],[...]]


i = 1
j = 1
T = []
T.append(lines[0][0]) 
Run Code Online (Sandbox Code Playgroud)

我这样做是为了避免IndexError(列出超出范围)在最后一行(i-1和东西).虽然,我认为这不是真正的蟒蛇方式.我也很感激这方面的帮助.

for i in lines:
    for j in lines:
        T[i][j] = lines[i][j] + max(T[i][j-1], T[i-1][j])
Run Code Online (Sandbox Code Playgroud)

这是发生错误的地方.如果已经存在i,我不应该得到什么.jint

python list typeerror indices

6
推荐指数
2
解决办法
4万
查看次数

Python:类型错误:列表索引必须是整数,而不是列表

我有两个坐标列表,它们看起来像这样:

list_kp2_ok:

[[1185.60009765625, 933.6000366210938], [1310.4000244140625, 828.0000610351562], [1067.0, 979.0], [1310.0, 828.0], [1423.2000732421875, 814.800048828125], [1306.0, 828.0], [3634.0, 605.0], [1308.0960693359375, 827.7120971679688], [1422.7200927734375, 815.0400390625], [1185.1199951171875, 933.1200561523438], [1186.56005859375, 923.0400390625], [1306.3681640625, 829.4401245117188], [1194.393798828125, 839.80810546875], [1187.1361083984375, 922.7520751953125], [1082.8800048828125, 849.6000366210938]]
Run Code Online (Sandbox Code Playgroud)

list_kp2_2_ok:

[[835.0, 1201.0], [1086.0, 850.0], [1187.0, 924.0], [1197.0, 839.0], [1310.0, 828.0], [3634.0, 605.0], [1195.2000732421875, 838.800048828125], [1308.0, 828.0000610351562], [1084.800048828125, 849.6000366210938], [1310.4000244140625, 828.0000610351562], [1186.800048828125, 924.0000610351562], [1296.0, 956.4000244140625], [1082.8800048828125, 849.6000366210938], [1072.800048828125, 944.6400146484375], [1083.4560546875, 850.1760864257812], [1187.1361083984375, 922.7520751953125], [3633.984375, 606.528076171875], [1082.4193115234375, 850.1761474609375], [1306.3681640625, 829.4401245117188], [1181.9521484375, 966.2977294921875], [1306.3682861328125, 828.6107788085938]]
Run Code Online (Sandbox Code Playgroud)

现在我需要检查两个列表上是否有任何相同的坐标并创建一个新的列表。所以我写道:

list_wsp=[]
count=0
count1=0
print …
Run Code Online (Sandbox Code Playgroud)

python loops list indices

4
推荐指数
1
解决办法
3万
查看次数

标签 统计

python ×3

indices ×2

list ×2

arrays ×1

loops ×1

python-3.x ×1

sum ×1

typeerror ×1