I have this list example list1=[['p1', 'p2', 'p3', 'p4'], ['p5', 'p6', 'p7']]
and if any variable is the same as other variable them split it in a group. Lets say p1 and p4 are the same and p5 and p6. So I want a new list that looks like list2=[['p1', 'p4'], ['p2', 'p3'], ['p5', 'p6'], 'p7']
. So how I need to divide them, pls help. I am using the newest version of python.
Ok to be more specific for "the same" in my program, I use p1 and p4 and if they give the same result for a certain character then I merge them in one group. Example
if dictionary.get(p1, character) is dictionary.get(p4, character)
if you have more questions just ask me.
The following will give you that result:
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]]
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']]
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]]
Using the unique_everseen
recipe and 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)]
Demo:
>>> 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]]
As you can see this also preserves the order of the items.
Code for unique_everseen
recipe:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.