Ted Idzikowski Ted Idzikowski - 1 year ago 69
Python Question

Printing items inside a list which have an element that occurs n times without using itemgetter

Having a 2D list, how do you find the elements inside the inner lists that occurs n time? For example, if:

>>> lst=[['Hey','Job','1998'],['No','Andrew','2011'],['Yes','Jack','2020'],['Pas','Job','2176'],['Hand','Andrew','1934'],['Fry','Job','1981']]

And the n occurence I'm looking for is at least 2, i.e. n >= 2.

How can I print something like below?

>>> Job with 3 occurrences
>>> Andrew with 2 occurrences

My attempt was not successful. And it also wasn't able to print as I wished above. Here it is:

>>> num = 2
>>> answer = [y for y in lst if lst.count(y[1]) >= int(num)]
>>> for i in answer:
a = ", ".join(str(x) for x in i)

If possible, avoid all kinds of collections such as dictionaries, maps or itemgetter. I would love seeing how a clever programmer would work this out using only lists and tuples.

Answer Source

The only other approach you could use involves two extra lists and, in all honesty, is a sub-par solution in comparison to the dict one that Oscar suggested.

You could do it, though, by creating a list of all relevant elements:

l = [i[1] for i in lst]

and then looping through these, counting their occurrence and adding them to a seen list so you don't count and print again:

seen = []
for i in l:
    if i in seen:
    c = l.count(i)
    if c >= 2:
        print("{} with {} occurences".format(i, c))

This prints out your wanted output.

Job with 3 occurences
Andrew with 2 occurences

You could use a set as seen for better performance of the if i in seen by using seen = {} and changing seen.append to seen.add. That's your call though, maybe sets are off the table too :-).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download