通过某列中的重复项在python中压缩列表列表

时间:2016-06-14 23:52:42

标签: python

所以,我在python中有一个列表列表,如下所示:

[[a, foo, bar], [a, dog, cat], [b, foo, bar], [c, foo, bar]]

我想将其浓缩为以下内容:

[[a, bar, cat], [b, bar], [c, bar]]

“a”对象的最后两个索引是原始列表中“a”对象的第一个和第二个实例的第3列。

我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以使用dict进行分组,使用第一个元素作为键并附加第三个元素:

const router = require('koa-router');
const { load } = require('some-other-lib');
const app = koa();
app.use(router(app));

app.get('load', loadjson);

function* loadJson() {
  this.body = yield new Promise(resolve => {
    load(result => resolve(result));
  });
}

如果你想保持秩序并删除包括第三个元素在内的欺骗行为,那么假设你只考虑第一个要考虑欺骗的元素:

l = [["a", "foo", "bar"], ["a", "dog", "cat"], ["b", "foo", "bar"], ["c", "foo", "bar"]]
from collections import defaultdict

d = defaultdict(list)
for a, b, c in l:
    d[a].append(c)

print([[k] + v for k,v in  d.items()])

如果订单无关紧要,只需使用设置l = [["a", "foo", "bar"], ["a", "dog", "cat"], ["a", "dog", "cat"], ["b", "foo", "bar"], ["c", "foo", "bar"],["b", "foo", "bar"]] from collections import defaultdict, OrderedDict d = defaultdict(OrderedDict) for a, b, c in l: d[a][c] = None print([[k] + list(v) for k,v in d.items()])