我想基于表2中显示的表2中的两个列表组合。
table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),
(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
Combined = [item for item in table2 if item[0] in table1]
print Combined
结果:
[]
期望的结果:
[(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim')]
答案 0 :(得分:3)
好的
table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
#convert to dictionaries (a more appropriate data structure,imho at least)
dict1=dict(table1)
dict2=dict((item[0],item[1:]) for item in table2)
#get the intersection
final = dict((key,dict2[key]+(dict1[key],)) for key in set(dict1).intersection(dict2))
print final
如果表格很大,你可能会看到显着的速度提升
答案 1 :(得分:2)
您的问题恰好在这里:
if item[0] in table1
相反,你应该将{1}元组的第一项与第1项中的第1项进行比较
item[0]
答案 2 :(得分:1)
如果您的表格始终具有您显示的格式,则可以执行以下操作:
Combined = []
for entry1 in table1:
for entry2 in table2:
if entry1[0]==entry2[0]:
Combined.append(entry2)
print Combined
答案 3 :(得分:0)
您的if item[0] in table1
子句正在测试是否可以在列表u'Id1'
中找到u'Id2'
和table1
等字符串。但是table1
是一个元组列表,这意味着你要将字符串与元组进行比较。不用说,str == tuple
将始终评估为False
。
要解决此问题,您可以使用其他列表解析:
>>> table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
>>> table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
>>> ids = [x[0] for x in table1]
>>> Combined = [item for item in table2 if item[0] in ids]
>>> Combined
[('Id1', 'Proudct1', None, 'New', 'Id#343', 'Jim')]
>>>
在上面的代码中,ids
将是table1
中找到的id字符串列表:
>>> table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
>>> ids = [x[0] for x in table1]
>>> ids
['Id1', 'Id4']
>>>
因此,if item[0] in table1
子句现在正在测试是否可以在字符串列表中找到item[0]
。
但请注意in
O(n)
将对ids
中的每个项目执行table2
(线性)搜索ids = {x[0] for x in table1}
。这可能很慢。更好的方法是使用一组id:
O(1)
使用in
设置{{1}}(常量)查找时间,因此重复查找时效率更高。
答案 4 :(得分:0)
我向table2添加了一个元素,以确保combined_list获得所需的内容。
table1 = [(u'Id1', u'New'), (u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),
(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim'),
(u'Id4', u'Proudct4', None, u'New', u'Id#44444', u'Jim')]
comined_list = []
for i in table1:
for j in table2:
if i[0] == j[0]:
comined_list.append(j)
print comined_list
输出:
[(u'Id1',u'Proudct1',None,u'New',u'Id#343',u'Jim'),(u'Id4',u'Proudct4',None,u'新的',你'#44444',u'Jim')]
答案 5 :(得分:0)
table1 = [(u'Id1', u'New'),(u'Id4', u'New')]
table2 = [(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim'),(u'Id2', u'Proudct2', None, u'New', u'Id#3343', u'Jim')]
st = {a for b in table1 for a in b}
print([x for x in table2 if x[0] in st])
[(u'Id1', u'Proudct1', None, u'New', u'Id#343', u'Jim')]