2013-07-25 2 views
1

데이터를 조 변경하려고하는데 zip 함수가 완벽하게 작동합니다. 가장 긴리스트를 찾고 루프를 통해 가지고있는 모든리스트에 적용하기 때문에, 많은 공백으로 끝납니다. 저에게이 출력을 제공목록에서 공백을 삭제합니다. 함수 python

Read_Data = inputdata.readlines() 
Length_Data = len(Read_Data) 
for a in range(Length_Data): 
    split_data = Read_Data[a].split(',') 

    zipper = zip(split_data) 
    print zipper 

(이 훨씬 더 큰 데이터 세트에서 단 하나 개의 예시 목록입니다) :

[('Abagrotis alternata',), ('Bignoniaceae',), ('Cruciferae',), ('Ericaceae',), ('Fagaceae',), ('Juglandaceae',), ('Oleaceae',), ('Pinaceae',), ('Rosaceae',), ('Solanaceae',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('\n',)] 

내가 만들어 많은 데이터를 가지고

내 코드입니다 이 목록의 수천. 공백을 삭제하는 방법이 있습니까? 아니면 모든 목록에있는 공백을 삭제할 수 있습니까? 내가 잘못이 이렇게 된 어떤 도움

주셔서 감사합니다 이것은 내 출력 등

**Lep. Species**    **Column** 
Abablemma brimleyana   Algae 
Abagrotis alternata    Bignoniaceae 
Abagrotis alternata    Cruciferae 
Abagrotis alternata    Ericaceae 
Abagrotis anchocelioides  Ericaceae 
Abagrotis anchocelioides  Rosaceae 

과 같이 할 것입니다 내 예를 들어 데이터

**Lep. Species**   **Column**  **Column** **Column** 
Abablemma brimleyana  Algae    
Abagrotis alternata   Bignoniaceae Cruciferae  Ericaceae   
Abagrotis anchocelioides Ericaceae  Rosaceae    
Abagrotis brunneipennis  Rosaceae  Ericaceae   
Abagrotis cryptica   Rosaceae  Salicaceae   
Abagrotis cupida   Ericaceae  Rosaceae  Salicaceae  
Abagrotis magnicupida  Asteraceae  Caryophyllaceae 

입니다.

내가 도움이 더 필요하다고 생각합니다. 다시 도움을 주셔서 감사합니다.

+0

빈 문자열이 항상 첫 번째 위치에 있습니까? –

+0

생성 된 모든 목록에 대해 다른 것은 없습니다 –

+2

'split_data '에'zip'이 실제로 당신을 여기에 오게할까요? 왜 그것을 압축하고있는거야? –

답변

1

filter()""의 튜플이 있습니다.

>>> testList = [('Abagrotis alternata',), ('Bignoniaceae',), ('Cruciferae',), ('Ericaceae',), ('Fagaceae',), ('Juglandaceae',), ('Oleaceae',), ('Pinaceae',), ('Rosaceae',), ('Solanaceae',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('',), ('\n',)] 
>>> filter(lambda x: not "" in x, testList) 
[('Abagrotis alternata',), ('Bignoniaceae',), ('Cruciferae',), ('Ericaceae',), ('Fagaceae',), ('Juglandaceae',), ('Oleaceae',), ('Pinaceae',), ('Rosaceae',), ('Solanaceae',), ('\n',)] 

목록은 파이썬에서 반복 가능합니다.

가 당신은 for i in range(len(...)) 방금 ​​또한

Read_Data = inputdata.readlines() 
for a in Read_Data: 
    #... 

에 코드를 줄일 수 할 필요가 없습니다, readlines()는 메모리에 전체 파일을 읽고

, 왜 대신 파일을 반복하지?

for a in f: 
    #... 
6
당신은 단순히 무시할 수

이/

zipper = zip(e for e in split_data if e) 

설명 내장 - 더 zip에 전달하기 전에 모든 빈 줄을 필터링 : 괄호없이

e for e in split_data if e 

, 위의 표현 generator expression입니다. list comprehension (대괄호 포함)과 달리 생성기 식은 built-inzip으로 전달되기 전에 전체 목록을 생성하지 않습니다.

with open('data.txt') as inputdata:       # open the file 
    for a in inputdata:           # iterate through the lines of the file 
    split_data = a.strip().split(',')       # strip the line (to remove `\n` and split it using ',' 
    zipper = zip(element for element in split_data if element) # create the zip while keeping only non empty elements 
+0

완벽하게 작동합니다. 'e'는 비어 있음을 의미합니까? –

+0

아무 e도 변수가 아닙니다. 당신의 마음이 원하는 경우 이국적인 이름을 사용할 수 있습니다. 그냥 빈 필드를 필터링하는 발전기 표현입니다. – Abhijit

+0

저는 초보 프로그래머입니다. 코드가 어떻게 작동하는지 설명해 주시겠습니까?다시 도움을 주셔서 감사합니다. –

0

다음 루프 표현의 동등을 제기 할 때까지 CSV 파일의 행과 열을 바꿔 쓰려고 할 때 잘못된 방향으로 가고 있습니다.

사용이 대신 :

import csv 

by_column = zip(*csv.reader(inputdata)) 

by_column 각 중첩 된 목록, 지금 inputdata 파일 객체의 열 목록의 목록입니다.

한 번에 한 행만 압축하면 빈 문자열 튜플은 단순히 빈 열입니다.

import csv 

with open('somefilename.csv', 'rb') as inputfile: 
    reader = csv.reader(inputfile) 
    for row in reader: 
     row = row[:2] 
     # process `row` further. It now only contains the first 2 columns. 
3

당신이 만약 : 그래서 그 단지 iterablezip 그 반복은 예외 StopIteration

익스프레션 당신은이 방법을 쓸 수

result = [] 
for e in split_data: 
    #Empty Check 
    if e: 
     result.append(e) 
+0

이것은 내가 원하는 것을 올바르게 수행하는 것처럼 보입니다. 예제 데이터와 출력을 보여 주었기 때문에 더 설명해 주시겠습니까? –

+1

@stagomight : 업데이트되었습니다. 다음 번에는 실제 작업으로 시작하십시오. 해결책이 아닐 수도 있습니다. :-) –

1

난 당신이 zip 기능의 작동 방식을 오해 있다고 생각 :

당신의 갱신을 보면, 당신이 정말로 원하는 것은 당신의 행을 슬라이스입니다.은 복수 목록 을 취하고 튜플 목록을 반환합니다. 예를 들어,

zipper = zip(["a", "b", "c"], [1, 2, 3]) 
print zipper 

가 출력

[('A', 1), ("B", 2), ("C", 3)]

하면 단일 목록과 함께 zip을 사용하고 있습니다. 결과는 각각 하나의 요소 만 갖는 튜플 목록입니다.

원래 문제를 해결하기 위해 zip을 사용하지 말고 데이터의 열과 행을 조 변경하는 것이 좋습니다. 조판을하기 전에 먼저 열과 행을 표현하는 방법을 찾아야합니다.

관련 문제