Python Extracts Elements That Match Two-Dimensional List Conditions

Asked 2 years ago, Updated 2 years ago, 17 views

I'd like to extract a list containing more than one identical element.

Specifically

 li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]

li contains two [1,2,3], three [2,3,4], and one [3,4,5][4,5,6][5,6,7] and
I would like to extract a list containing two or more identical elements and obtain results similar to li2 below.

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

Thank you for your cooperation.

python

2022-09-30 16:42

3 Answers

This is an example of Python 3 running

 li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
from collections import Counter
c=Counter(map(tuple,li))

Finally, if the li2 element doesn't have to be a list:

 li2=list(filter(lambdax:c[x]>1,c))

If it has to be a list:

 li2=list(map(list,filter(lambdax:c[x]>1,c)))

If you also want to keep the order:

 li2=sorted(list(map(list,filter(lambdax:c[x]>1,c))),key=li.index)


2022-09-30 16:42

Method 1
how to use itertools.groupby.When the same elements are sorted and aligned, they are grouped together.The order of results is not maintained.

 from ittertools import groupby
print [k for k, gin groupby(sorted(li)) iflen(list(g))>=2]

Method 2
Using collections.Counter, the order of results is not maintained.

import collections

li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
li2=map(lambda(k,v):list(k),#Tuple only and return to list
          filter(lambda(x,v): Extract 2 or more as a result of counting v>=2,#Counter
                 collections.Counter(
                     Make it a hashable tuple to count in map(tuple,li)#Counter
                 ).items()
          )
)
print li2

Run Results

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


2022-09-30 16:42

I have already answered, but I feel that List Compression is more refreshing than map or lambda.

 from collections import Counter
li = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [2, 3, 4], [1, 2, 3], [2, 3, 4], [5, 6, 7]]
c=Counter(tuple(items) for items in li)
more_than_one = [ items for items, count in c. most_common() if count > 1 ]

more_than_one:

[(2,3,4), (1,2,3)]


2022-09-30 16:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.