Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
Run Code Online (Sandbox Code Playgroud)
这是有意的吗?我强烈记得早期版本的回归int/int=int?我应该怎么做,是否有新的分区运算符或者我必须总是演员?
我查了类似的帖子,人们发布的例子就像我自己的版本一样向我抛出同样的错误.我一直得到错误"列表索引必须是整数,而不是浮点数." 我相信我在获得中位数背后的逻辑很好,但我无法弄清楚如何解决这个问题.我知道这是因为5/2 = 2.5并且这不是一个有效的索引,但在这种情况下我怎么能得到偶数列表的中位数呢?
我的简短代码是:
def median(lst):
lst.sort()
a = len(lst)
if a % 2 == 0:
b = lst[len(lst)/2]
c = lst[(len(lst)/2)-1]
d = (b + c) / 2
return d
if a % 2 > 0:
return lst[len(lst)/2]
myList = [1,8,10,11,5]
myList2 = [10,5,7,2,1,8]
print(median(myList))
print(median(myList2))
Run Code Online (Sandbox Code Playgroud)
我尝试这样做来修复它但仍然出现同样的错误:
def median(list):
list.sort()
a = float(len(list))
if a % 2 == 0:
b = float(list[len(list)/2])
c = float(list[(len(list)/2)-1])
d = (b + c) / 2.0
return float(d)
if a % 2 …Run Code Online (Sandbox Code Playgroud) 我是python的新手,我必须创建一个打印用户输入字符串的中间字符的程序.这是我有的:
#accept string from user then print middle character
x = input("Enter a string: ")
print(x[len(x)/2-1])
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行该程序时,我不断收到此错误:
"TypeError:字符串索引必须是整数".
我不知道如何解决这个问题或如何让这个程序工作.请帮忙!