我有元组列表:
foo = [(1, 5), (1, 3), (1, 9), (2, 8), (2, 3), (3, 1)]
我正在尝试将值从 foo 分配到arrayof 中arrays,结果应如下所示:
_result[0] = []
_result[1] = [5, 3, 9]
_result[2] = [8, 3]
_result[3] = [1]
这是我的代码:
_result = [[]]
for x,y in foo:
_result[x].append(y)
但我收到一个错误:
IndexError: list index out of range
我应该如何解决它?
编辑:
结果不必安排
零位置的数组应包含一个空字段
该示例很简单,但foo也可以包含其他值,例如:
foo = [(9, 5), (10, 3), (10, 9), (5, 8), (5, 3), (9, 1)]
结果:
_result[0] = []
_result[1] = []
_result[2] = []
_result[3] = []
_result[4] = []
_result[5] = [8, 3]
_result[6] = []
_result[7] = []
_result[8] = []
_result[9] = [5, 1]
_result[10] = [3, 9]
所以所有不在位置的值都x应该包含an empty field在给定的索引上
跃然一笑
拉风的咖菲猫
相关分类