gpt4 book ai didi

python - 为什么我的代码得不到预期的返回?

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:52 26 4
gpt4 key购买 nike

grade=['Ben Anderson',95,90,100,-1,'Mary Johnson',75,78,79,-5,'Michael Walter',80,68,0]   

def convert_grades(lst):
a = []
b = []
for i in lst:
if isinstance(i,str):
c = 0
while lst[c] < 0 or lst[c] == []:
a = a + lst[c]
c = c + 1
b = b + a
return b

我希望它返回为

[['Ben Anderson',95,90,100],['Mary Johnson',75,78,79],['Michael Walter',80,68,0]]

但它返回为 []

不知道怎么回事。需要帮助。

最佳答案

输入输出形式相同的建议:

def convert_grades(lst):
out = []
for element in grade:
if isinstance(element, str):
buf = [] # re-initializes 'buf' everytime there is a string
out.append(buf)
buf.append(element)
return out

前代码非pythonicity的三个主要表现:

  1. 在已经熟悉 python 习语的人会使用类型方法的情况下使用算术运算符(在这种情况下为 list.append);
  2. 在列表中输入,其中明显的数据类型应该是字典(尽管并不总是可以控制获取数据的方式);
  3. 而且,最严重的症状是输出是列表的列表,而实际上是在求字典。

因此,一种更 Pythonic 的方式,返回字典而不是列表:

def convert_grades(lst):
out = {}
for element in grade:
if isinstance(element, str):
key = element
out[key] = []
else:
out[key].append(element) ## mind that this would raise an error if first element in lst is not string
return out

print convert_grades(grade)

希望这对您有所帮助!

关于python - 为什么我的代码得不到预期的返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11961422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com