在python中的列表中插入项目

时间:2015-08-24 07:40:47

标签: python django list

我在下面有这个查询:

high_results = list(
    high_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name')))
high_results.insert(0, 3)

medium_results = list(
    medium_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name')))
medium_results.insert(0, 2)

low_results = list(low_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name')))
low_results.insert(0, 1)

我想在列表中插入一个项目,但问题是,结果不对。

[3, ["Unknown", "Residential", 128], 2, ["Unknown", "Residential", 243], 1, ["Rural Health Center", "Other Government Offices", 1], ["Unknown", "Residential", 384], ["Katugasan Multi-Purpose Gym", "Sport Center/Gymnasium/Covered Court", 1], ["Katugasan Elementary School", "School", 5]]

它没有括在括号中,也没有分开。我该如何解决? 输出应该是这样的:

[ [3,"Unknown", "Residential", 128],  [2,"Unknown", "Residential", 243], [ 1,"Rural Health Center", "Other Government Offices", 1],...]

输出:

# Combine all of the structures into a unified response
results = list(chain(high_results, medium_results, low_results))

2 个答案:

答案 0 :(得分:2)

您似乎将high_results作为列表中的列表。比较

>>> high_results = [["Unknown", "Residential", 128]]
>>> high_results.insert(0, 3)
>>> high_results
[3, ['Unknown', 'Residential', 128]]

>>> high_results = [["Unknown", "Residential", 128]]
>>> high_results[0].insert(0, 3)
>>> high_results
[[3, 'Unknown', 'Residential', 128]]

如果high_results有多个元素,并且您希望将3添加到每个元素

high_results = [[3] + x for x in high_results]

同样适用于其他人

答案 1 :(得分:1)

您似乎希望将此结果添加到查询中的每个结果集。这最好用列表理解来完成:

high_results = [(3,) + row for row in high_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]
medium_results =  [(2,) + row for row in medium_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]
low_results = [(1,) + row for row in low_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]

(3,) +前缀比high_results.insert(0, 3)调用更容易理解,这也需要您转换每个嵌套元组,然后在循环中应用list.insert()调用。

您可以将这些列表连接在一起,而不是在此处使用chain()

output = high_results + medium_results + low_results