【发布时间】:2021-06-27 20:00:42
【问题描述】:
我正在使用一个 api,它返回格式为类似于此的字典列表(列表)的 json:
list_of_dictionaries = [
[{'key1':0},{'key2':1}],
[{'key1':2},{'key2':3}],
[{'key1':4},{'key2':5}],
[{'key1':6},{'key2':7}],
[{'key1':8},{'key2':9}]
]
我还有一个单独的包含坐标的元组列表:
coordinates_tuple = namedtuple('Coordinates', ['x','y'])
coordinates_list = []
coordinates_list.append(coordinates_tuple((0),(0)))
coordinates_list.append(coordinates_tuple((1),(0)))
coordinates_list.append(coordinates_tuple((1),(1)))
coordinates_list.append(coordinates_tuple((0),(1)))
coordinates_list.append(coordinates_tuple((-1),(-1)))
我的目标是将每个坐标元组作为键/值对添加到 list_of_dictionaries 中,因此我创建了这个 for 循环,似乎可以实现所需的输出:
for i in range(len(list_of_dictionaries)):
x = coordinates_list[i].x
y = coordinates_list[i].y
coordinates_dictionary = {'x' : x , 'y' : y}
list_of_dictionaries[i].append(coordinates_dictionary.copy())
print(list_of_dictionaries[i])
#output
#[{'key1': 0}, {'key2': 1}, {'x': 0, 'y': 0}]
#[{'key1': 2}, {'key2': 3}, {'x': 1, 'y': 0}]
#[{'key1': 4}, {'key2': 5}, {'x': 1, 'y': 1}]
#[{'key1': 6}, {'key2': 7}, {'x': 0, 'y': 1}]
#[{'key1': 8}, {'key2': 9}, {'x': -1, 'y': -1}]
假设这两个列表总是相同的长度并按顺序排列(coordinates_list[0] 将与 list_of_dictionaries[0] 匹配)- 这种方法是否有意义或有更好的解决方案?
【问题讨论】:
-
注意,你显示的是字典列表...
-
您正在遍历字典列表的 len,但您正在使用索引在坐标列表中查找值。您是否预见到它可能会超出索引范围?
-
@JoeFerndz 他说“假设这两个列表的长度总是相同的”
-
此外,您正在遍历字典列表,但也附加到相同的字典列表。我不建议这样做。循环可能会变得混乱
-
@JoeFerndz 该列表是二维的。他正在添加到内部列表,而不是他正在迭代的列表。
标签: python list dictionary