如何将元组列表中的值分配到数组中

我有元组列表:


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在给定的索引上


杨魅力
浏览 139回答 2
2回答

跃然一笑

你可以在dict这里使用。前任:foo = [(1, 5), (1, 3), (1, 9), (2, 8), (2, 3), (3, 1)]result = {}for k, v in foo:    result.setdefault(k, []).append(v)print(result) # -->{1: [5, 3, 9], 2: [8, 3], 3: [1]}您也可以使用collections.defaultdict而不是setdefault

拉风的咖菲猫

length = 0_result = [[]]for x, y in foo:    if x > length:        for i in range(x - length):            _result.append([])        length = length + x    _result[x].append(y)您的代码中的问题:您无法访问列表中不存在项目的索引位置。您不能追加到不存在的列表。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python