itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)


문제 설명

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, 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:
        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ópezDimitris Fasarakis HilliardAdam Van ProoyenChiheb NexusCopperfield)

참조 문서

  1. Printing items inside a list which have an element that occurs n times without using itemgetter (CC BY‑SA 2.5/3.0/4.0)

#list #Python #python-3.x #matrix






관련 질문

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

포스트백 후 모든 항목이 손실되는 CheckBoxList 컨트롤 (CheckBoxList control losing all items after post back)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)

잘못된 값을 얻는 목록 확인 후 (After list checking getting wrong value)

결과를 세로 방향으로 저장하는 방법 (How do i save the result in a Vertical direction)

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)

R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)

python, 출력으로 코딩하는 동안 pycharm에서 이 메시지를 받았습니다. :TypeError: can't convert type 'list' to numerator/denominator (python , I got this message in pycharm while coding as output :TypeError: can't convert type 'list' to numerator/denominator)







코멘트