Programing

목록의 내용을 가져 와서 다른 목록에 추가

lottogame 2020. 5. 22. 08:05
반응형

목록의 내용을 가져 와서 다른 목록에 추가


목록의 내용을 가져 와서 다른 목록에 추가하는 것이 합리적인지 이해하려고합니다.

루프 함수를 통해 생성 된 첫 번째 목록이 있는데, 파일에서 특정 줄을 가져 와서 목록에 저장합니다.

그런 다음 두 번째 목록을 사용하여 이러한 줄을 저장하고 다른 파일에서 새주기를 시작합니다.

내 생각은 한 번주기가 완료되면 목록을 가져 와서 두 번째 목록으로 덤프 한 다음 새주기를 시작하고 첫 번째 목록의 내용을 두 번째 목록으로 다시 덤프하지만 추가하면 두 번째 목록이됩니다. 내 루프에서 작성된 모든 작은 목록 파일의 합계. 특정 조건이 충족되는 경우에만 목록을 추가해야합니다.

다음과 비슷한 모양입니다.

# This is done for each log in my directory, i have a loop running
for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    for item in list1:
        if "string" in item: #if somewhere in the list1 i have a match for a string
            list2.append(list1) # append every line in list1 to list2
            del list1 [:] # delete the content of the list1
            break
        else:
            del list1 [:] # delete the list content and start all over

이것이 합리적입니까 아니면 다른 경로로 가야합니까?

로그 목록이 길고 각 텍스트 파일이 상당히 크기 때문에 너무 많은주기를 거치지 않는 효율적인 것이 필요합니다. 그래서 목록이 목적에 맞을 것이라고 생각했습니다.


아마 원하는

list2.extend(list1)

대신에

list2.append(list1)

차이점은 다음과 같습니다.

>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]

list.extend()임의의 iterable을 허용 하므로 대체 할 수도 있습니다

for line in mylog:
    list1.append(line)

으로

list1.extend(mylog)

작은 목록을 복사하지 않고 여러 개의 작은 목록을 하나의 큰 목록으로 (또는 적어도 하나의 큰 반복 가능한 것으로) 처리하는 빠른 방법 itertools.chain살펴보십시오 .

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

당신이하려는 일에 상당히 합리적입니다.

파이썬에서 많은 노력을 기울이는 약간 짧은 버전은 다음과 같습니다.

for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    if any(True for line in list1 if "string" in line):
        list2.extend(list1)
    del list1

    ....

The (True for line in list1 if "string" in line) iterates over list and emits True whenever a match is found. any() uses short-circuit evaluation to return True as soon as the first True element is found. list2.extend() appends the contents of list1 to the end.


Using the map() and reduce() built-in functions

def file_to_list(file):
     #stuff to parse file to a list
     return list

files = [...list of files...]

L = map(file_to_list, files)

flat_L = reduce(lambda x,y:x+y, L)

Minimal "for looping" and elegant coding pattern :)


To recap on the previous answers. If you have a list with [0,1,2] and another one with [3,4,5] and you want to merge them, so it becomes [0,1,2,3,4,5], you can either use chaining or extending and should know the differences to use it wisely for your needs.

Extending a list

Using the list classes extend method, you can do a copy of the elements from one list onto another. However this will cause extra memory usage, which should be fine in most cases, but might cause problems if you want to be memory efficient.

a = [0,1,2]
b = [3,4,5]
a.extend(b)
>>[0,1,2,3,4,5]

enter image description here

Chaining a list

Contrary you can use itertools.chain to wire many lists, which will return a so called iterator that can be used to iterate over the lists. This is more memory efficient as it is not copying elements over but just pointing to the next list.

from itertools import chain
a = [0,1,2]
b = [3,4,5]
c = itertools.chain(a, b)

enter image description here

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.


If we have list like below:

list  = [2,2,3,4]

two ways to copy it into another list.

1.

x = [list]  # x =[] x.append(list) same 
print("length is {}".format(len(x)))
for i in x:
    print(i)
length is 1
[2, 2, 3, 4]

2.

x = [l for l in list]
print("length is {}".format(len(x)))
for i in x:
    print(i)
length is 4
2
2
3
4

You can also combine two lists (say a,b) using the '+' operator. For example,

a = [1,2,3,4]
b = [4,5,6,7]
c = a + b

Output:
>>> c
[1, 2, 3, 4, 4, 5, 6, 7]

참고URL : https://stackoverflow.com/questions/8177079/take-the-content-of-a-list-and-append-it-to-another-list

반응형