Programing

Python : n 개의 목록을 만드는 가장 빠른 방법

lottogame 2020. 9. 14. 21:36
반응형

Python : n 개의 목록을 만드는 가장 빠른 방법


그래서 빈 목록 목록을 가장 잘 만드는 방법이 궁금합니다.

[[],[],[]...]

파이썬이 메모리의 목록과 함께 작동하는 방식 때문에 작동하지 않습니다.

[[]]*n

이것은 생성 [[],[],...]되지만 각 요소는 동일한 목록입니다.

d = [[]]*n
d[0].append(1)
#[[1],[1],...]

목록 이해와 같은 것이 작동합니다.

d = [[] for x in xrange(0,n)]

그러나 이것은 루핑을 위해 Python VM을 사용합니다. 묵시적 루프를 사용하는 방법이 있습니까 (C로 작성된 이점을 활용)?

d = []
map(lambda n: d.append([]),xrange(0,10))

이것은 실제로 더 느립니다. :(


아마 조금 더 빠른 유일한 방법은

d = [[] for x in xrange(n)]

이다

from itertools import repeat
d = [[] for i in repeat(None, n)]

int매 반복마다 객체 를 만들 필요가 없으며 내 컴퓨터에서 약 5 % 더 빠릅니다.

편집 : NumPy를 사용하면 다음을 사용하여 Python 루프를 피할 수 있습니다.

d = numpy.empty((n, 0)).tolist()

그러나 이것은 실제로 목록 이해보다 2.5 배 느립니다.


목록 이해는 실제로 명시 적 루프 ( 예 : 함수 dis출력 참조)보다 더 효율적으로 구현 되며 map방법은 매 반복마다 ophaque 호출 가능 객체를 호출해야하므로 상당한 오버 헤드가 발생합니다.

그럼에도 불구하고 [[] for _dummy in xrange(n)]그것을 수행하는 올바른 방법이며 다양한 다른 방법 간의 작은 속도 차이 중요하지 않습니다. 물론이 작업에 대부분의 시간을 소비하지 않는 한-이 경우 대신 알고리즘 작업을해야합니다. 이 목록을 얼마나 자주 만드십니까?


다음은 달콤하고 단순한 (및 개념적) 두 가지 방법이고 다른 하나는보다 형식적이며 데이터 세트를 읽은 후 다양한 상황에서 확장 할 수 있습니다.

방법 1 : 개념

X2=[]
X1=[1,2,3]
X2.append(X1)
X3=[4,5,6]
X2.append(X3)
X2 thus has [[1,2,3],[4,5,6]] ie a list of lists. 

방법 2 : 공식 및 확장 가능

다른 번호 목록으로 목록을 저장하는 또 다른 우아한 방법-파일에서 읽습니다. (여기 파일에는 데이터 셋 train이 있습니다.) Train은 50 개의 행과 20 개의 열로 구성된 데이터 세트입니다. 즉. Train [0]은 csv 파일의 첫 번째 행을 제공하고 train [1]은 두 번째 행을 제공하는 식입니다. 여기에 설명 된 변수 인 0 열을 제외하고는 50 개의 행이있는 데이터 세트를 하나의 목록으로 분리하는 데 관심이 있으므로 원래 기차 데이터 세트에서 제거해야합니다. . 이를 수행하는 코드는 다음과 같습니다.

설명 변수에만 관심이 있으므로 내부 루프의 "1"에서 읽습니다. 그리고 다른 루프에서 X1 = []을 다시 초기화합니다. 그렇지 않으면 X2.append ([0 : (len (train [0])-1)])가 X1을 반복해서 다시 작성합니다.

X2=[]
for j in range(0,len(train)):
    X1=[]
    for k in range(1,len(train[0])):
        txt2=train[j][k]
        X1.append(txt2)
    X2.append(X1[0:(len(train[0])-1)])

To create list and list of lists use below syntax

 x = [[] for i in range(10)]

this will create 1-d list and to initialize it put number in [[number] and set length of list put length in range(length)

  • To create list of lists use below syntax.

    x = [[[0] for i in range(3)] for i in range(10)]

this will initialize list of lists with 10*3 dimension and with value 0

  • To access/manipulate element

    x[1][5]=value


So I did some speed comparisons to get the fastest way. List comprehensions are indeed very fast. The only way to get close is to avoid bytecode getting exectuded during construction of the list. My first attempt was the following method, which would appear to be faster in principle:

l = [[]]
for _ in range(n): l.extend(map(list,l))

(produces a list of length 2**n, of course) This construction is twice as slow as the list comprehension, according to timeit, for both short and long (a million) lists.

My second attempt was to use starmap to call the list constructor for me, There is one construction, which appears to run the list constructor at top speed, but still is slower, but only by a tiny amount:

from itertools import starmap
l = list(starmap(list,[()]*(1<<n)))

Interesting enough the execution time suggests that it is the final list call that is makes the starmap solution slow, since its execution time is almost exactly equal to the speed of:

l = list([] for _ in range(1<<n))

My third attempt came when I realized that list(()) also produces a list, so I tried the apperently simple:

l = list(map(list, [()]*(1<<n)))

but this was slower than the starmap call.

Conclusion: for the speed maniacs: Do use the list comprehension. Only call functions, if you have to. Use builtins.

참고URL : https://stackoverflow.com/questions/5518435/python-fastest-way-to-create-a-list-of-n-lists

반응형