“ TypeError:只能将列表(而不是“ str”)连接到列表”是什么意思?

时间:2019-01-04 13:40:17

标签: python python-3.x

我已经尝试了一切,但我的老师却无济于事

print("Input a list of data into the function: median([d1, d2,d3, ...])")

def median(data):
    data = sorted(data)
    center = int(len(data)/2.0)
    if len(data)%2.0==0:
        return print("Your median is", str([(len(data))/2.0])+([((len(data)/2.0)+1)/2] +"."))
    else:
        return print("Your median is", str(data[center]) +".")

我需要计算中位数。

1 个答案:

答案 0 :(得分:1)

问题:

# s => string
# l => list

str([(len(data))/2.0]) + ( [((len(data)/2.0)+1)/2] + "." )
# ssssssssssssssssssss + ( lllllllllllllllllllllll + sss )

+运算符已重载以将字符串添加到字符串或将列表添加到列表:

print('Hello ' + 'World') # 'Hello World'
print( [1] + [2]) # [1,2]

它不了解列表+字符串,因此会出错。


您几乎可以找到解决方案。您可以通过使用地板划分并重新使用已经计算过的center来使情况变得更好-这使if len(data)%2.0 == 0:更加容易理解:

def median(data):
    ll = len(data)
    if ll == 0:
        return ""
    data = sorted(data)
    center = ll//2    # use floor div to get an integer
    if ll%2.0 == 0:
        med = (data[center-1] + data[center])/2.0 
    else:
        med = data[center]
    return "Your median is {}.".format(med) 

测试:

for l in [[1], [1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]:
    print(l,median(l)) )

输出:

[1] Your median is 1.
[1, 2] Your median is 1.5.
[1, 2, 3] Your median is 2.
[1, 2, 3, 4] Your median is 2.5.
[1, 2, 3, 4, 5] Your median is 3.