python - 结合两个列表 Python

标签 python python-2.7

我想根据表 2 中出现在表 1 中的 ID 合并两个列表。

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')]

最佳答案

还好

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

如果你的表很大,你可能会看到显着的速度提升

关于python - 结合两个列表 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27429021/

相关文章:

python - 如何将数据框中的一列转换为python中的二维数组

python - 字典到日期时间

python - Pandas Loc 按索引选择以及单个表达式中的 bool 条件

python - 将 python.exe 重命名为 python3.exe 以便与 Windows 上的 python2 共存

python-2.7 - 安装/启动 pgadmin4 时出错需要 SQLAlchemy 1.1.0 或更高版本

python - Image in Image with cvMatchTemplate - 但是怎么做呢?

写入文件时将 Python unicode 转换为 ASCII

python - sci-kit learn GridSearchCV 的一致答案

python - 如何使用 python 的标准库 zipfile 检查 zip 文件是否加密?

python - 如何高效的传递函数?