我有一个数组arr = [title,fileurl],所以当我打印arr时,它是这样的:
['name1', 'url1']
['name1', 'url2']
['name1', 'url3']
['name2', 'url1']
['name2', 'url2']
['name3', 'url1']
我想按第一个元素对这些数组进行分组,这意味着我想拥有:
['name1', 'url1', 'url2', 'url3']
['name2', 'url1', 'url2']
['name3', 'url1']
我的代码:
for final in posterlink:
pagesourcec = requests.get(final)
soupc = BeautifulSoup(pagesourcec.text, "html.parser")
strc = soupc.findAll("iframe", attrs={"id": "myframe"})
title = soupb.find("li",{"class": "breadcrumb-item active"}).get_text()
for embedlink in strc:
fff = embedlink.get('data-src')
arr = [title, fff]
print arr
答案 0 :(得分:4)
您可以这样做:
from collections import defaultdict as ddict
group = ddict(list)
for name, url in arr:
group[name].append(url)
如果您绝对希望将其作为列表列表,则可以执行以下操作:
group = [[name, *urls] for name, urls in group.items()]
编辑:务必注意,以上代码适用于python 3,无论如何,这都是您应该使用的。但是,为了完整起见,如果您使用的是python 2.7,请使用以下代码:
group = [[name] + urls for name, urls in group.items()]
答案 1 :(得分:-1)
尝试一下:
a = [['name1', 'url1'],
['name1', 'url2'],
['name1', 'url3'],
['name2', 'url1'],
['name2', 'url2'],
['name3', 'url1']]
d = {}
for elem in a:
if elem[0] not in d:
d[elem[0]] = []
d[elem[0]].append(elem[1:])
输出:
{'name1': [['url1'], ['url2'], ['url3']],
'name2': [['url1'], ['url2']],
'name3': [['url1']]}