다음 파이썬 코드는 2D 배열을 opportunity()
. 함수에서 각 행의 길이가 미리 정의 된 크기보다 큰지 확인합니다. 조건이 참이면 h 번째 요소가 목록에 추가됩니다.
다음으로 배열에서 가장 빈번한 숫자를 검색합니다.
from collections import Counter
def opportunity(a,h):
ar = []
ar.append( [row[h] for row in a if len(row)>h] )
b = Counter(ar)
return b.most_common(1)
next = opportunity(take, head)
따라서 다음과 같은 입력을 위해
1 3 3
2 4
5 2 4 6 2
4 3 6 1
3 7 2 6 1 5
h=3
출력은 다음과 같아야 한다고 가정 합니다.
ar = [6 1 6]
next = 6
하지만이 오류가 발생합니다.
File "c:\Users\mahmood\python_ws\first.py", line 43, in <module>
next = opportunity(take, head)
File "c:\Users\mahmood\python_ws\first.py", line 12, in opportunity
b = Counter(ar)
File "C:\Python34\Lib\collections\__init__.py", line 475, in __init__
self.update(*args, **kwds)
File "C:\Python34\Lib\collections\__init__.py", line 562, in update
_count_elements(self, iterable)
builtins.TypeError: unhashable type: 'list'
목록 이해력을 사용하여 새 목록을 만들고 있으므로 ar (카운터가 목록을 계산할 수 없기 때문에 문제의 원인)에 추가하는 대신 Counter에서 목록 이해를 수행하십시오.
달성하려는 작업을 수행하는 방법은 다음과 같습니다.
# Create a one dimensional list using a list comprehension which gets the h'th element if the length of row > h
def opportunity(a,h):
ar = [row[h] for row in a if len(row)>h]
return Counter(ar).most_common(1)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다