가장 빠른 길은 지정하십시오. 값을 다운로드되었는지 존재하는 목록 (수백만 개의 값을 바뀌엇어요 항목이없습니다) 및 그 index) 는?
내가 알고 있는 모든 값을 고유하도록 예제에서와 목록에 있다.
a = [4,2,3,1,5,6]
if a.count(7) == 1:
b=a.index(7)
"Do something with variable b"
a = [4,2,3,1,5,6]
try:
b=a.index(7)
except ValueError:
"Do nothing"
else:
"Do something with variable b"
a = [4,2,3,1,5,6]
if 7 in a:
a.index(7)
내 첫 번째 방법은 크게 두 번째 방법은 실제 코드, 3.81 삼성전자와 1.88 초 걸린다.
내가 할 수 있는 블렌더 apiu 액세스함으로써 입자의 목록:
particles = [1, 2, 3, 4, etc.]
여기에서 I 액세스하려면 particle& # 39 의 위치:
particles[x].location = [x,y,z]
내가 이웃이 있을 경우 각 입자의 위치 및 테스트 검색을 통해 각 입자가 같은 있습니다.
if [x+1,y,z] in particles.location
"Find the identity of this neighbour particle in x:the particle's index
in the array"
particles.index([x+1,y,z])
다른 사람이 ',' 에서 언급된 바와 같이 매우 느린 대규모 열거합니다 수 있습니다. 다음은 ',' 세트 '와' 양분하다 '에서 "이라며" 에 대한 비교. 시간 (초) 가 로그에서는 기록하십시오 배율입니다.
코드는 테스트:
import random
import bisect
import matplotlib.pyplot as plt
import math
import time
def method_in(a,b,c):
start_time = time.time()
for i,x in enumerate(a):
if x in b:
c[i] = 1
return(time.time()-start_time)
def method_set_in(a,b,c):
start_time = time.time()
s = set(b)
for i,x in enumerate(a):
if x in s:
c[i] = 1
return(time.time()-start_time)
def method_bisect(a,b,c):
start_time = time.time()
b.sort()
for i,x in enumerate(a):
index = bisect.bisect_left(b,x)
if index < len(a):
if x == b[index]:
c[i] = 1
return(time.time()-start_time)
def profile():
time_method_in = []
time_method_set_in = []
time_method_bisect = []
Nls = [x for x in range(1000,20000,1000)]
for N in Nls:
a = [x for x in range(0,N)]
random.shuffle(a)
b = [x for x in range(0,N)]
random.shuffle(b)
c = [0 for x in range(0,N)]
time_method_in.append(math.log(method_in(a,b,c)))
time_method_set_in.append(math.log(method_set_in(a,b,c)))
time_method_bisect.append(math.log(method_bisect(a,b,c)))
plt.plot(Nls,time_method_in,marker='o',color='r',linestyle='-',label='in')
plt.plot(Nls,time_method_set_in,marker='o',color='b',linestyle='-',label='set')
plt.plot(Nls,time_method_bisect,marker='o',color='g',linestyle='-',label='bisect')
plt.xlabel('list size', fontsize=18)
plt.ylabel('log(time)', fontsize=18)
plt.legend(loc = 'upper left')
plt.show()
['세트'] [1] 항목을 넣어 수 있습니다. 조회를 설정되었습니다 매우 효율적이다.
종료기:
s = set(a)
if 7 in s:
# do stuff
[1]: http://docs.python.org/library/stdtypes.html # 추상형데이터타입 설정되었습니다 프로첸스트 설정되었습니다
def check_availability(element, collection: iter):
return element in collection
check_availability('a', [1,2,3,4,'a','b','c'])
내가 믿을 수 있는 가장 빠른 방법은 다운로드되었는지 선택한 값은 어레이입니다.
a = [4,2,3,1,5,6]
index = dict((y,x) for x,y in enumerate(a))
try:
a_index = index[7]
except KeyError:
print "Not found"
else:
print "found"
이렇게 하면 좋은 아이디어 있으면 이벤트여야만 doesn& # 39, 우리가 할 수 있는 t change it 부품 및 카타시안 딕트 () 는 한 번 사용 후 거듭했다. 만약 a 는 바꼈소, 자세히 설명하는 제공하십시오 너희는너희가 거지.
이 말은 응용 프로그램을 사용할 수 있는 지정값이 게인에서 블룸 필터 데이터 구조.
블룸 필터 조회, 한 마디로 말할 수 없는 경우 말해둘꼐요 세트의 값은 매우 빠르게 있습니다. 그렇지 않으면 속도가 조회 할 수 있는 값을 얻을 수 있을 것으로 색인입니다 지정값이 명단요 그래서 응용 프로그램의 경우, " 내려받습니다 found" 경향이 있지 않습니다. 그 결과 훨씬 더 자주 " found"; 블룸 필터 추가하여 속도를 결과가 나타날 수 있습니다.
자세한 내용은 어떻게 블룸 필터는, 웹 검색 优秀 개요입니다 위키백과 는 파이썬 블룸 필터 library" "; 적어도 몇 유용한 구현을 제공할 것이다.
이 점을 유념하십시오 '평등' 의 테스트 ('=') 뿐 아니라 연산자입니다 아이디 ('는') 에 대한 '의' 논리학 'list 는 거의 동등한 수준의 다음 (it& # 39 의 파이썬 표시되어도 스피통 에서 C 로 짜여진 아니라 실제로 적어도):
>. 요소에 대한 s: >. 만약 요소는 대상: >. # 빠른 확인할지 아이디 한다는 것은 >. 진정한 반품하십시오. >. 만약 요소 = 대상: >. # 느린 확인할지 실제 평등 >. 진정한 반품하십시오. >. 거짓값 반품하십시오.
하지만 대부분의 경우 이 상세 정보는 관련이 없는 상황에 따라 수도 있지만, 예를 들어, '속성' 는 파이썬 초보 깜짝 놀라게 한 것은 남겨두십시오 누마피.난 있다 없는 비유하 자체에 대한:
>>> import numpy
>>> numpy.NAN == numpy.NAN
False
>>> numpy.NAN is numpy.NAN
True
>>> numpy.NAN in [numpy.NAN]
True
이런 특이한 구별할 수 있는 건 ' ()' 같은 사용할 수 있습니다.
>>> lst = [numpy.NAN, 1 , 2]
>>> any(element == numpy.NAN for element in lst)
False
>>> any(element is numpy.NAN for element in lst)
True
'의' 논리학 ' ()' 와 '목록 기록하십시오 대한 모든 것:
any(element is target or element == target for element in lst)
그러나 이것이 내가 강조하십시오 모서리입니다 경우 대부분의 경우 '과' 에서 작동자 매우 최적화 및 정확히요 그리웠댔지 물론 (통칭 '목록' 또는 '세트' 를 통해).
코드, 그러나 매우 빠른 검색을 위해 알고리즘입니다 아닙니다.
목록 및 그 가치를 찾고자 하는 경우, 이 숫자를 모두 무척 간단합니다. 만약 문장열: 아래에는:
또한, 필요한 경우 원래 위치를 니 번호 여바바 이에 대한 두 번째, 인덱스 컬럼.
이 방법을 사용할 수 없게 될 경우 목록은 숫자, 그리고 있지만, 여전히 빠른 비교 / 수 있는 함수를 정의하여 써줬지 주문하십시오 할 수 있습니다.
물론 이 요구를 있지만 이 같은 투자 확대를 위한 목록을 확인, 자꾸 정렬할지 () 메서드를 재사용합니다 그만한 가치가 있을 수 있습니다.
"' a = [4.2,3.1,5.6]
인덱스화할 딕트 = (x, y 에 대해 열거합니다. (x, y) (a))
b = 이네스트제 (7, 없음) 만약 b 가 없는 없음: 뭔가 b" 가변적입니다 함께 "; "'
이 방법은 대비하여 '그냥' 이제 (key, 기본), t # 39 의 딕트 작성하더라도 can& 때 중요한 것입니다. , 는 χ02 경우 키 값을 되돌려줍니다 (딕트 것과 ' [핵심]') 이 있지만, 그렇지 않은 경우 () '' 이제 너회의 되돌려줍니다 기본값입니다 (here '없음'). 이 경우 해당 사탄들 해야 합니다 'a' 의 기본 않을 것입니다.
처음 질문으로 없었다.
>. 가장 빠른 길은 지정하십시오. 값을 다운로드되었는지 존재하는 바뀌엇어요 (목록 >. 수백만 개의 값을 항목이없습니다) 및 그 index) 는?
따라서 다음 두 가지 사항을 찾기:
백업이었습니다 항목이 목록, 1. 2. 지정하십시오. 인덱스 (목록에서 경우).
나는 이 모든 경우에, 추가된 인덱스화합니다 @xslittlegrass 수정되었음 향해, 연산 코드를 추가로 메서드입니다.
흥미롭게도 이 및 시도하시겠습니까 설정되었습니다 avamer 방식이 시간.
import random
import bisect
import matplotlib.pyplot as plt
import math
import timeit
import itertools
def wrapper(func, *args, **kwargs):
" Use to produced 0 argument function for call it"
# Reference https://www.pythoncentral.io/time-a-python-function/
def wrapped():
return func(*args, **kwargs)
return wrapped
def method_in(a,b,c):
for i,x in enumerate(a):
if x in b:
c[i] = b.index(x)
else:
c[i] = -1
return c
def method_try(a,b,c):
for i, x in enumerate(a):
try:
c[i] = b.index(x)
except ValueError:
c[i] = -1
def method_set_in(a,b,c):
s = set(b)
for i,x in enumerate(a):
if x in s:
c[i] = b.index(x)
else:
c[i] = -1
return c
def method_bisect(a,b,c):
" Finds indexes using bisection "
# Create a sorted b with its index
bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0])
for i,x in enumerate(a):
index = bisect.bisect_left(bsorted,(x, ))
c[i] = -1
if index < len(a):
if x == bsorted[index][0]:
c[i] = bsorted[index][1] # index in the b array
return c
def method_reverse_lookup(a, b, c):
reverse_lookup = {x:i for i, x in enumerate(b)}
for i, x in enumerate(a):
c[i] = reverse_lookup.get(x, -1)
return c
def profile():
Nls = [x for x in range(1000,20000,1000)]
number_iterations = 10
methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup]
time_methods = [[] for _ in range(len(methods))]
for N in Nls:
a = [x for x in range(0,N)]
random.shuffle(a)
b = [x for x in range(0,N)]
random.shuffle(b)
c = [0 for x in range(0,N)]
for i, func in enumerate(methods):
wrapped = wrapper(func, a, b, c)
time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations)))
markers = itertools.cycle(('o', '+', '.', '>', '2'))
colors = itertools.cycle(('r', 'b', 'g', 'y', 'c'))
labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse'))
for i in range(len(time_methods)):
plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels))
plt.xlabel('list size', fontsize=18)
plt.ylabel('log(time)', fontsize=18)
plt.legend(loc = 'upper left')
plt.show()
profile()
이 협력했습니다 가져다줄래요: (목록 번역, 한 줄 광고문)
[list_to_search_in.index(i) for i in list_from_which_to_search if i in list_to_search_in]
내가 가진 모든 항목 및 list_to_search_in 'a' 와 'list_from_which_to_search indexe 반품하십시오 있는 항목의' 싶었다.
이 인덱스를 되돌려줍니다 좋은 목록.
코드 확인하기 위해 존재하는 두 요소 시스템을스토리지 시스템을 제품 는 k:
n = len(arr1)
for i in arr1:
if k%i==0:
print(i)