我有一个无法解决的嵌套列表问题。
first_list = cursor.execute('SELECT id, number, code FROM test').fetchall()
second_list = cursor.execute('SELECT key FROM test2').fetchall()
second_set = set(second_list)
results = []
for id, number, code in first_list:
name = [code]
for a in second_set:
if code.startswith(a[0]):
if a[0] not in name:
name.append(a[0])
results.append(tuple(name))
print (id, code, name)
这会产生一个输出:
('1', '98', ['1', '2'])
('2', '12', ['1', '2', '3'])
我想知道列表理解的最佳方法是什么,以便输出为:
('1', '98', '1')
('1', '98', '2')
('2', '12', '1')
('2', '12', '2')
('2', '12', '3')
答案 0 :(得分:4)
您可以使用嵌套列表解析来执行此操作:
results = [(code, a[0])
for id, number, code in first_list
for a in second_set
if code.startswith(a[0])]
您可能想要second_set
一组只 a[0]
值:
second_set = {a[0] for a in second_list}
简化列表理解中的一些事情
results = [(code, a)
for id, number, code in first_list
for a in second_set if code.startswith(a)]
您的示例输出似乎基于print
语句,而不是附加到result
列表的实际值。您的print
语句也包含id
值;如果需要,只需将其添加到:
results = [(id, code, a)
for id, number, code in first_list
for a in second_set if code.startswith(a)]