-3

如何像这样比较多个元组列表:

[[(1,2), (3,6), (5,3)], [(1,5), (3,5)], [(2,1), (1,8), (3,9)]]

输出应该是:

[(1,2), (1,5), (1,8)],[(3,6), (3,5), (3,9)]

这意味着我只想要那些x 轴值与其他值匹配的值。
(5,3) 和 (2,1) 应该被丢弃!

4

4 回答 4

1

也许你正在寻找链接这个:

l = [[(1,2), (3,6), (5,3)], [(1,5), (3,5)], [(2,1), (1,8), (3,9)]]
output = [l[0][0], l[1][0], l[2][1]], [l[0][1], l[1][1], l[2][2]]
于 2013-02-22T05:36:54.953 回答
1

一种可能的选择

>>> def group(seq):
    for k, v in groupby(sorted(chain(*seq), key = itemgetter(0)), itemgetter(0)):
        v = list(v)
        if len(v) > 1:
            yield v


>>> list(group(some_list))
[[(1, 2), (1, 5), (1, 8)], [(3, 6), (3, 5), (3, 9)]]

另一个受欢迎的选择

>>> from collections import defaultdict
>>> def group(seq):
    some_dict = defaultdict(list)
    for e in chain(*seq):
        some_dict[e[0]].append(e)
    return (v for v in some_dict.values() if len(v) > 1)

>>> list(group(some_list))
[[(1, 2), (1, 5), (1, 8)], [(3, 6), (3, 5), (3, 9)]]

那么他们中的哪一个更适合示例数据呢?

>>> def group_sort(seq):
    for k, v in groupby(sorted(chain(*seq), key = itemgetter(0)), itemgetter(0)):
        v = list(v)
        if len(v) > 1:
            yield v


>>> def group_hash(seq):
    some_dict = defaultdict(list)
    for e in chain(*seq):
        some_dict[e[0]].append(e)
    return (v for v in some_dict.values() if len(v) > 1)

>>> t1_sort = Timer(stmt="list(group_sort(some_list))", setup = "from __main__ import some_list, group_sort, chain, groupby")
>>> t1_hash = Timer(stmt="list(group_hash(some_list))", setup = "from __main__ import some_list, group_hash,chain, defaultdict")
>>> t1_hash.timeit(100000)
3.340240917954361
>>> t1_sort.timeit(100000)
0.14324535970808938

并且有一个更大的随机列表

>>> some_list = [[sample(range(1000), 2) for _ in range(100)] for _ in range(100)]
>>> t1_sort.timeit(100)
1.3816694363194983
>>> t1_hash.timeit(1000)
34.015403087978484
>>> 
于 2013-02-22T05:43:45.093 回答
0
>>> L=[[(1,2), (3,6), (5,3)], [(1,5), (3,5)], [(2,1), (1,8), (3,9)]]
>>> from collections import defaultdict
>>> from itertools import chain
>>> p = defaultdict(list)
>>> for i in chain.from_iterable(L):
...  p[i[0]].append(i)
... 
>>> p = {k:v for k,v in p.items() if len(v)>1}
>>> p.values()
[[(1, 2), (1, 5), (1, 8)], [(3, 6), (3, 5), (3, 9)]]
于 2013-02-22T05:45:29.237 回答
0

这很好用:

>>> l=[[(1,2), (3,6), (5,3)], [(1,5), (3,5)], [(2,1), (1,8), (3,9)]]
>>> [[t for t in [i for sub in l for i in sub] if t[0]==1]]+[[t for t in [i for sub in l for i in sub] if t[0]==3]]
[[(1, 2), (1, 5), (1, 8)], [(3, 6), (3, 5), (3, 9)]]

或者,不重复:

>>> flat=[i for sub in l for i in sub]
>>> [[t for t in flat if t[0]==1]]+[[t for t in flat if t[0]==3]] 
[[(1, 2), (1, 5), (1, 8)], [(3, 6), (3, 5), (3, 9)]]
于 2013-02-22T05:48:58.170 回答