如何在python中划分列表?

时间:2014-04-20 14:23:09

标签: python list python-3.4

我有这个列表示例 list1=[['p1', 'p2', 'p3', 'p4'], ['p5', 'p6', 'p7']]如果任何变量与其他变量相同,则将它分组。让我们说p1和p4是相同的,p5和p6。所以我想要一个看起来像的新列表 list2=[['p1', 'p4'], ['p2', 'p3'], ['p5', 'p6'], 'p7']。所以我需要如何划分它们,请帮忙。我使用的是最新版本的python。

确定更具体的"相同"在我的程序中,我使用p1和p4,如果它们为某个字符给出相同的结果,那么我将它们合并到一个组中。实施例

if dictionary.get(p1, character) is dictionary.get(p4, character)

如果你有更多问题请问我。

2 个答案:

答案 0 :(得分:2)

以下内容将为您提供结果:

list1=[[1, 2, 2, 1], [3, 4, 3]]

print [[item]*lst.count(item) for lst in list1 for item in list(set(lst))]

[OUTPUT]
[[1, 1], [2, 2], [3, 3], [4]]

示例1

list1=[['hello', 'hello', 'hello', 'what'], ['i', 'am', 'i']]

print [[item]*lst.count(item) for lst in list1 for item in list(set(lst))]

[OUTPUT]
[['what'], ['hello', 'hello', 'hello'], ['i', 'i'], ['am']]

示例2

list1=[[1,2,3,2,1],[9,8,7,8,9],[5,4,6,4,5]]

print [[item]*lst.count(item) for lst in list1 for item in list(set(lst))]

[OUTPUT]
[[1, 1], [2, 2], [3], [8, 8], [9, 9], [7], [4, 4], [5, 5], [6]]

答案 1 :(得分:1)

使用unique_everseen食谱和collections.Counters

from collections import Counter

def solve(lst):
    counters = map(Counter, lst)
    return [ [uniq]*c[uniq] for seq, c in zip(lst, counters)
                                                for uniq in unique_everseen(seq)]

<强>演示:

>>> print(solve([[1, 2, 2, 1], [3, 4, 3]]))
[[1, 1], [2, 2], [3, 3], [4]]
>>> print(solve([['hello', 'hello', 'hello', 'what'], ['i', 'am', 'i']]))
[['hello', 'hello', 'hello'], ['what'], ['i', 'i'], ['am']]
>>> print(solve([[1,2,3,2,1],[9,8,7,8,9],[5,4,6,4,5]]))
[[1, 1], [2, 2], [3], [9, 9], [8, 8], [7], [5, 5], [4, 4], [6]]

如您所见,这也保留了项目的顺序。


unique_everseen食谱的代码:

from itertools import filterfalse

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element