排序不完全相同的列表Python

时间:2012-09-08 22:18:40

标签: python list sorting

我有两个清单。

一个列表仅包含代码,例如:

b3b
3cd
6f6
4d8
96b
00a
774
eb3
607
7e5

另一个列表包含具有名称的代码,例如

b3b:John
607:Eric
7e5:Jarrold

但是这个名单尚未完成。

我想要的是输出,因为另一个不能被移除并且必须以正确的顺序,例如。

b3b:John
3cd
6f6
4d8
96b
00a
774
eb3
607:Eric
7e5:Jarrold

已经拥有此代码,但它只返回True或False,但这不是我想要的。

list1 = [line.strip() for line in open('list1')]
list2 = [line.strip() for line in open('list2')]

comp = [i[:3] for i in list2]

for i in list1:
    print(i, i in list2)

也许有人可以帮我解决这个问题?

1 个答案:

答案 0 :(得分:5)

您应该使用字典映射键来代替名称而不是列表作为第二个数据结构:

with open("list1") as f:
    keys = [line.strip() for line in f]
with open("list2") as f:
    names = dict(line.strip().split(":", 1) for line in f)

现在您可以有效地实现循环:

for k in keys:
    print(k, names.get(k, ""))

list2中为list1的每个条目执行线性搜索效率相当低。除了更好的性能外,字典也是更好的数据含义模型。