문제 설명
itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)
2D 목록이 있는 경우 내부 목록에서 n번 발생하는 요소를 어떻게 찾습니까? 예를 들면:
>>> lst=[['Hey','Job','1998'],['No','Andrew','2011'],['Yes','Jack','2020'],['Pas','Job','2176'],['Hand','Andrew','1934'],['Fry','Job','1981']]
그리고 내가 찾고 있는 n번은 적어도 2, 즉 n >= 2인 경우입니다.
아래와 같은 것을 어떻게 인쇄할 수 있습니까? ?
6>>> Job with 3 occurrences
>>> Andrew with 2 occurrences
시도가 실패했습니다. 또한 위에서 원하는 대로 인쇄할 수 없었습니다. 여기 있습니다:
>>> 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)
print(a)
가능하면 사전, 지도 또는 itemgetter와 같은 모든 종류의 컬렉션을 피하십시오. 똑똑한 프로그래머가 목록과 튜플만 사용하여 이 문제를 해결하는 방법을 보고 싶습니다.
참조 솔루션
방법 1:
With the restriction that no external modules are allowed, this is how I'd write it:
result = {}
for _, name, _ in lst:
if name in result:
result[name] += 1
else:
result[name] = 1
num = 2
for name, count in result.items():
if count >= num:
print("'{}' with {} occurrences".format(name, count))
If you were allowed to use additional modules, a much simpler solution would be to use a Counter
object:
from collections import Counter
result = Counter(name for _, name, _ in lst)
방법 2:
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, count
ing 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:
continue
c = l.count(i)
if c >= 2:
print("{} with {} occurences".format(i, c))
seen.append(i)
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 :‑).
방법 3:
You could use the get
method on python dicts
which is the same thing as dict[key]
except if the key is not in the dictionary it returns the second argument:
counts = {}
for _, name, _ in lst:
counts[name] = counts.get(name, 0) + 1
for name, count in counts:
if count < n:
continue
print("'{}' with {} occurrences".format(name, count))
방법 4:
You updated your question a lot of times and i was trying to give you a new approch to have the same output as you gave.
As i see your last update you said that you want to
avoid all kinds of collections such as dictionaries, maps or itemgetter. And you would love seeing how a clever programmer would work this out using only lists and tuple
So, in my solution i will use groupby
from itertools
module. And my approch is like this example:
from itertools import groupby
lst=[['Hey','Job','1998'],['No','Andrew','2011'],['Yes','Jack','2020'],['Pas','Job','2176'],['Hand','Andrew','1934'],['Fry','Job','1981']]
groups = {}
for k, _ in groupby(lst, lambda x: x[1]):
if k not in groups:
groups[k] = 1
else:
groups[k] +=1
print("\n".join(x for x in ["'{0}' with {1} occurences".format(i, groups[i]) for i in groups if groups[i] >=2]))
Output:
'Job' with 3 occurences
'Andrew' with 2 occurences
방법 5:
here is another way, similar to the one of Jin, but with only one extra list and count on the fly
>>> lst=[['Hey','Job','1998'],['No','Andrew','2011'],['Yes','Jack','2020'],['Pas','Job','2176'],['Hand','Andrew','1934'],['Fry','Job','1981']]
>>> count=[]
>>> for _,name,_ in lst:
ready=False
for i,(_,n) in enumerate(count):
if name==n:
count[i][0] += 1
ready=True
break
if not ready:
count.append( [1,name] )
>>> count.sort(reverse=True)
>>> count
[[3, 'Job'], [2, 'Andrew'], [1, 'Jack']]
>>> for c,n in count:
if c>=2:
print("{} with {} occurrences".format(n,c))
Job with 3 occurrences
Andrew with 2 occurrences
>>>
(by user6945769、Óscar López、Dimitris Fasarakis Hilliard、Adam Van Prooyen、Chiheb Nexus、Copperfield)