I have the following list in Python:
l = [[2], [3], [2, 2], [5], [2], [3], [7], [2, 2, 2], [3, 3], [2], [5], [11], [2, 2], [3], [13], [2], [7], [3], [5], [2, 2, 2, 2], [17], [2], [3, 3], [19], [2, 2], [5]]
I want to write a function that will return the uniquely-valued sublists of maximum length. In this case, the function would return:
l = [[5], [7], [3, 3], [11], [13], [2, 2, 2, 2], [17], [19]]
I am still a beginner at python, and I have very little idea as to how to write such a function, however. The furthest I got was figuring out that I could iterate over the sublists by using nested loops. But from what I've seen of Python, it seems like there must be some simpler way to return the list I am looking for than using loops.
Update:
Here's what I was doing with the code: solving project euler #5, the non-brute force way!
I'm sure this code could be refactored, but whatever.
Thanks for your help, guys. itemgetter
was just what I needed.
#!/usr/bin/python
# coding = UTF-8
import argparse, sys, math
from itertools import groupby
from collections import defaultdict
from operator import itemgetter
parser = argparse.ArgumentParser()
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args:
intinput = int(sys.argv[1])
elif not sys.stdin.isatty():
intinput = int(sys.stdin.read())
else:
parser.print_help()
def prime_factorize(n):
factors = []
number = math.fabs(n)
while number > 1:
factor = get_next_prime_factor(number)
factors.append(factor)
number /= factor
if n < -1:
factors[0] = -factors[0]
return factors
def get_next_prime_factor(n):
if n % 2 == 0:
return 2
for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2):
if n % x == 0:
return x
return int(n)
def mkfactors(n):
tpf = []
for i in range(n+1):
tpf.extend(prime_factorize(i))
return tpf
l = [list(g) for k,g in groupby(mkfactors(intinput))]
m = [max(g) for _,g in groupby(sorted(l,key=itemgetter(0)),key=itemgetter(0))]
prod = 1
for list in m:
for element in list:
prod *= element
print prod
If you know that every sublist has the same elements, you can do:
l = [[2], [3], [2, 2], [5], [2], [3], [7], [2, 2, 2], [3, 3], [2], [5], [11], [2, 2], [3], [13], [2], [7], [3], [5], [2, 2, 2, 2], [17], [2], [3, 3], [19], [2, 2], [5]]
from collections import defaultdict
my_dict = defaultdict(list)
for ele in l:
if len(my_dict[ele[0]]) < len(ele):
my_dict[ele[0]] = ele
Result:
>>> my_dict.values()
[[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
The easiest thing to do here is to use a data structure that makes the problem simple, and then you can always convert back after the fact.
For example, a dict
mapping keys (primes) to lengths (exponents) is easy. So:
>>> l = [[2], [3], [2, 2], [5], [2], [3], [7], [2, 2, 2], [3, 3], [2], [5], [11], [2, 2], [3], [13], [2], [7], [3], [5], [2, 2, 2, 2], [17], [2], [3, 3], [19], [2, 2], [5]]
>>> d = {}
>>> for sublist in l:
... value, count = sublist[0], len(sublist)
... if count > d.get(value, 0):
... d[value] = count
>>> d
{2: 4, 3: 2, 5: 1, 7: 1, 11: 1, 13: 1, 17: 1, 19: 1}
It should be obvious how to turn that back into a list
of list
s, so I'll leave that to you.
Note that this loses the order, but you can trivially fix that with OrderedDict
. It also loses list
identity—eg, the [2, 2, 2, 2]
that you get back at the end will be equal to , but not the same as , the original [2, 2, 2, 2]
. But that's easy to fix too—just stored the sublist
directly instead of using count
. Anyway, I don't think either of these is relevant to your problem.
l = [[2], [3], [2, 2], [5], [2], [3], [7], [2, 2, 2], [3, 3], [2], [5], [11], [2, 2], [3], [13], [2], [7], [3], [5], [2, 2, 2, 2], [17], [2], [3, 3], [19], [2, 2], [5]]
l = [max(i for i in l if j in i) for j in (2, 3, 5, 7, 11, 13, 17, 19)]
print(l)
# [[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
I guess all it is is just a list comprehension with nested for loops, but it works fine.
using collections.Counter
and sets
:
In [47]: s=set([x[0] for x in lis])
In [48]: c=[Counter(x) for x in lis]
In [49]: [max(c,key=lambda y:y[x]) for x in s]
Out[49]:
[Counter({2: 4}),
Counter({3: 2}),
Counter({5: 1}),
Counter({7: 1}),
Counter({11: 1}),
Counter({13: 1}),
Counter({17: 1}),
Counter({19: 1})]
Another way:
In [64]: from collections import defaultdict
In [65]: d=defaultdict(list)
In [66]: for x in lis:
d[x[0]].append(len(x))
....:
In [67]: [[x]*max(y) for x,y in d.items()]
Out[67]: [[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
from itertools import groupby
from operator import itemgetter
[max(g) for _,g in groupby(sorted(l),key=itemgetter(0))]
out:
[[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
A straightforward solution would be to convert the sorted list to a dict with key as the first element of the list, which would eventually remove duplicates based on key.
>>> {e[0]: e for e in sorted(l)}.values()
[[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
for Python Version < 2.7 where dict comprehension is not available
>>> dict((e[0], e) for e in sorted(l)).values()
[[2, 2, 2, 2], [3, 3], [5], [7], [11], [13], [17], [19]]
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.