我尝试将列表分成三个新列表,但似乎我的方法存在问题。你能帮助我看看我该怎么做吗?谢谢!
quiz = [[91, 94, 38, 48, 70, 85, 94, 59], [78, 96, 90, 55, 77, 82, 94, 60], [99, 94, 82, 77, 75, 89, 94, 93], [49, 92, 75, 48, 80, 95, 99, 98]]
midterm = []
final = []
我试图让测验得到列表的前五个数字,midterm然后有接下来的两个,而final有列表的最后一个数字:
quiz = [[91, 94, 38, 48, 70,], [78, 96, 90, 55, 77], [99, 94, 82, 77, 75,], [49, 92, 75, 48, 80]]
midterm = [[85, 94,],[82, 94,], [89, 94,], [95, 99,]]
final = [[59], [60], [93], [98]]
这是我的代码:
quiz = [[91, 94, 38, 48, 70, 85, 94, 59], [78, 96, 90, 55, 77, 82, 94, 60], [99, 94, 82, 77, 75, 89, 94, 93], [49, 92, 75, 48, 80, 95, 99, 98]]
midterm = quiz[5:2]
final = midterm[5:1]
答案 0 :(得分:1)
midterm = [i[5:7] for i in quiz]
final = [i[7:] for i in quiz]
quiz = [i[:5] for i in quiz]
这是如何运作的:
[]是for循环的精简版本。 例如,上面的代码与以下代码相同:
for i in quiz:
midterm.append(i[5:7])
for i in quiz:
final.append(i[7:])
tmp = []
for i in quiz:
tmp.append(i[:5])
quiz = tmp
它几乎遍历测验中的所有元素,并将两个和一个和五个用于单独的数组。你做错了的是你没有将测验视为二维数组,而是作为一维数组。
您当前的代码采用数组测验的第二到第五个元素作为期中考试,恰好是第二到第五个整数数组,而不是测验中每个数组的第二到第五个整数。
答案 1 :(得分:0)
在这里:使用list comprehension
>>> quiz = [[91, 94, 38, 48, 70, 85, 94, 59], [78, 96, 90, 55, 77, 82, 94, 60], [99, 94, 82, 77, 75, 89, 94, 93], [49, 92, 75, 48, 80, 95, 99, 98]]
>>> new_quiz = [ x[:5] for x in quiz ]
>>> mid_term = [ x[5:7] for x in quiz ]
>>> final = [ x[-1:] for x in quiz ]
>>> new_quiz
[[91, 94, 38, 48, 70], [78, 96, 90, 55, 77], [99, 94, 82, 77, 75], [49, 92, 75, 48, 80]]
>>> mid_term
[[85, 94], [82, 94], [89, 94], [95, 99]]
>>> final
[[59], [60], [93], [98]]