我有一个长度为14的项目列表:
html_doc = [u'Crabtree Conservation Area - Number 28',
u'Conservation Area',
u'Environment Agency Flood Risk Zone 3',
u'Flood Risk Zone 3',
u'Environment Agency Flood Risk Zone 2',
u'Flood Risk Zone 2',
u'Buildings Structures And Works Exceeding 90 Metres',
u'Aerodrome Safeguarding London Heathrow 1',
u'Controlled Parking Zone T',
u'Controlled Parking Zone T',
u'Flood Zone 3 Low Residual Risk',
u'Flood Zone 3 Low Residual Risk',
u"Embankment Residents' Association",
u"Embankment Residents' Assoc."]
数组中的每个元素应该组合在一起作为“Name”:“Constraint_type”意味着列表的第一个和第二个元素是相关的。
我有这个我认为不会起作用的代码:
for i in xrange(len(html_doc)):
dict.append("Name:" html_doc[i], "Constraint_Type": html_doc[i+1])
对此有什么看法?
答案 0 :(得分:3)
html_dict = dict(zip(html_doc[::2], html_doc[1::2]))
答案 1 :(得分:3)
使用iter
与dict
和zip
配对并创建每两个元素的键/值:
it = iter(html_doc)
print(dict(zip(it,it)))
{u'Buildings Structures And Works Exceeding 90 Metres': u'Aerodrome Safeguarding London Heathrow 1', u'Flood Zone 3 Low Residual Risk': u'Flood Zone 3 Low Residual Risk', u"Embankment Residents' Association": u"Embankment Residents' Assoc.", u'Crabtree Conservation Area - Number 28': u'Conservation Area', u'Controlled Parking Zone T': u'Controlled Parking Zone T', u'Environment Agency Flood Risk Zone 3': u'Flood Risk Zone 3', u'Environment Agency Flood Risk Zone 2': u'Flood Risk Zone 2'}
如果您对列表进行切片,则会创建两个新列表。
答案 2 :(得分:1)
您可以使用step
中的xrange
参数:
for i in xrange(0, len(html_doc), 2):
dict[html_doc[i]] = html_doc[i+1]
如果您使用xrange
,则 start
需要step
参数。如果您使用步骤,xrange
将生成[start, start+step, start+2*step ... ]
答案 3 :(得分:0)
我认为这是一种非常易读的方法:
d = {}
while html_doc:
d[html_doc.pop()] = html_doc.pop()
,并提供:
>>> d
{u'Buildings Structures And Works Exceeding 90 Metres': u'Aerodrome Safeguarding London Heathrow 1',
u'Controlled Parking Zone T': u'Controlled Parking Zone T',
u'Crabtree Conservation Area - Number 28': u'Conservation Area',
u"Embankment Residents' Association": u"Embankment Residents' Assoc.",
u'Environment Agency Flood Risk Zone 2': u'Flood Risk Zone 2',
u'Environment Agency Flood Risk Zone 3': u'Flood Risk Zone 3',
u'Flood Zone 3 Low Residual Risk': u'Flood Zone 3 Low Residual Risk'}