我正在使用scholar_info['department']=[s.find('a')['href'], s.find('a').contents[0]]
从sqlite表中提取数据,这当然会抓取包含相关snip1
值的每一行。 id
列表现在看起来像services
。
我希望能够将元组列表的列表排序为更易于管理的数据集。合并所有相关的ID集。
例如,output1
变为[(10, u'80'), (10, u'443')]
,当然所有其他条目都添加到同一{10: 80, 443}
。
我很难对数据进行排序。我如何比较同一列表中的项目?下面的dict
显示清理的数据,但我不确定如何从中获取干净的字典。
snip1
example1
OUTPUT1
c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()
示例1
[[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
OUTPUT2
data = [(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
for item in data:
for i in item:
print i #output2
答案 0 :(得分:1)
d = {}
for item in data:
d[item[0][0]] = []
for i in item:
d[i[0]] = d[i[0]] + [int(i[1])]
答案 1 :(得分:1)
使用dict
和list
理解
>>> data = [[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')],
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')],
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
>>> output = {record[0][0]: [int(item[1]) for item in record] for record in data}
>>> output
{2: [22],
3: [25],
4: [443],
5: [443],
6: [443],
7: [22],
8: [80],
9: [443],
10: [80, 443],
11: [80, 443],
12: [80, 443],
13: [443],
14: [80, 443],
15: [25]}
答案 2 :(得分:1)
将元组列表转换为字典:
list = [(10, u'80'), (10, u'443')]
dict = {}
for (i, j) in list:
dict.setdefault(i, []).append(j)
这会给你:
>>> dict
{10: [u'80', u'443']}
然后,您可以使用pprint以便于比较字典项的方式进行打印。
import pprint
pprint.pprint(dict)
示例只有一个键,但是pprint会为每个键创建一个新行,类似于你所拥有的那些键。