类型错误:只能将列表(不是“int”)连接到 python 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17755220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:06:16  来源:igfitidea点击:

TypeError: can only concatenate list (not "int") to list in python

python

提问by Tung Pham

I tried to run this code, but it showed an error:

我尝试运行此代码,但显示错误:

def shoot(aliens):

    s=[0]*1000
    s[0]=0
    s[1]=1
    num=len(aliens)
    b=[[0 for m in range(1000)] for n in range(1000)]
    for j in xrange(2,num):
        for i in xrange(0,j):

                b[j][i]=s[i]+min(int(aliens[j]),f[j-i]) ##Error here
        s[j]=max(b)

and the error:

和错误:

Traceback (most recent call last):
File "module1.py", line 67, in <module>
print shoot(line)
File "module1.py", line 26, in shoot
b[j][i]=s[i]+min(int(aliens[j]),f[j-i])
TypeError: can only concatenate list (not "int") to list

please help!

请帮忙!

Edit: added more code. s, aliens and f are other arrays. I tried to save the result to the 2 dimentional array, but it showed that error.

编辑:添加了更多代码。s、aliens 和 f 是其他数组。我试图将结果保存到二维数组中,但它显示了该错误。

回答by nicolas.leblanc

try:

尝试:

b=[[0 for m in range(1000)] for n in range(1000)]
    for j in xrange(2,num):
        for i in xrange(0,j):
             b[j][i] = s[j][i] + min(int(aliens[j]),f[j-i])

It seems to me likes is a 2D list (list of a list), and thus, you can't perform the operation.

在我看来,喜欢的是一个 2D 列表(列表的列表),因此,您无法执行该操作。

s[j] + min(int(aliens[j]),f[j-i])

回答by user2357112 supports Monica

s[j] = max(b)

doesn't treat bas a 2-d array of integers and pick the biggest one. bis a list of lists. max(b)compares the lists and returns the one that compares highest. (List comparison is done by comparing the elements lexicographically.)

不会将其b视为二维整数数组并选择最大的一个。b是一个列表列表。max(b)比较列表并返回比较最高的列表。(列表比较是通过按字典顺序比较元素来完成的。)

You want

你要

s[j] = max(max(sublist) for sublist in b)

回答by caytekin

I got the same error with the following python code:

我使用以下 python 代码遇到了同样的错误:

 retList = []
    for anItem in aList:
        if anItem % 2 == 0:
            retList = retList + anItem
    return retList

when I changed the "+" which I used for concatenation to an append statement:

当我将用于连接的“+”更改为 append 语句时:

 retList = []
    for anItem in aList:
        if anItem % 2 == 0:
            retList.append(anItem) 
    return retList

it worked fine.

它工作正常。