Ped*_*que 11 python dictionary list
我有我国家的报纸网站的网址和标题列表。作为一般示例:
x = ['URL1','news1','news2','news3','URL2','news1','news2','URL3','news1']
Run Code Online (Sandbox Code Playgroud)
每个URL元素都有一个对应的“新闻”元素序列,其长度可以不同。在上面的示例中,URL1有3个对应的新闻,URL3只有一个。
有时,URL没有相应的“新闻”元素:
y = ['URL4','news1','news2','URL5','URL6','news1']
Run Code Online (Sandbox Code Playgroud)
我可以轻松找到每个URL索引以及每个URL的“新闻”元素。
我的问题是:是否可以将此列表转换成以URL元素为键而“ news”元素为列表/元组值的字典?
预期产量
z = {'URL1':('news1', 'news2', 'news3'),
'URL2':('news1', 'news2'),
'URL3':('news1'),
'URL4':('news1', 'news2'),
'URL5':(),
'URL6':('news1')}
Run Code Online (Sandbox Code Playgroud)
我在这篇文章中看到了类似的问题,但是并不能解决我的问题。
For*_*Bru 11
您可以这样做:
>>> y = ['URL4','news1','news2','URL5','URL6','news1']
>>> result = {}
>>> current_url = None
>>> for entry in y:
... if entry.startswith('URL'):
... current_url = entry
... result[current_url] = ()
... else:
... result[current_url] += (entry, )
...
>>> result
{'URL4': ('news1', 'news2'), 'URL5': (), 'URL6': ('news1',)}
Run Code Online (Sandbox Code Playgroud)