2017-01-29 12 views
1

중첩 배열의 양쪽 정렬 된 열을 제목 상태로 만드는 것입니다. 그러나 나는 그것을 풀 수있는 방법을 알아낼 수 없다. 따라서이 배열은 ..Python : 중첩 배열의 열 정렬

tableData = [['apples', 'oranges', 'cherries', 'banana'], 
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']] 

이 내가 (정렬을 통지) 달성하고자하는 것입니다 :

apples Alice dogs 
oranges Bob cats 
cherries Carol moose 
    banana David goose 

내가 성공적으로 하위 배열의 각을 정당화하기 위해 코드를 생성 할 수 있었지만 내 결과는 단순히 수직적이다. 주로 행과 열로 만드는 코드를 찾지 못했기 때문에 주로 긴 단일 열만 있습니다. 내 결과가 보이는 같은 :

apples 
oranges 
cherries 
    banana 
Alice 
    Bob 
Carol 
...#you get the picture 

편집 : 그래서 내 질문은 이미 예 (하위 배열의 수) 배열의 메타 데이터를 모르는 당신을 가정 3 개 개의 컬럼으로 그것을 깰 얼마나 간단

난 그냥 돕기 위해 내 코드를 포함하지만 적은에서이 할 수에서 어떤 사람들 확신

#function to get the longest word in the sub-array 
#to determine justification length 
def maxLength(someList): 
    count = {} 
    max_num = 0 
    for item in someList: 
     count[item] = len(item) 
    for value in count.values(): 
     if value > max_num: 
      max_num = value 
    return(max_num) 

#function to store the length of the longest words 
#of each sub-array into an array 
def maxWidths(tableData): 
    widths = [] 
    for i in range(len(tableData)): 
     widths.insert(i,maxLength(tableData[i])) 
    return(widths) 

#function to print table(this is the part that needs work)      
def printTable(tableData): 
    widths = maxWidths(tableData) 
    for i in range(len(tableData)): 
     for item in tableData[i]: 
      print(item.rjust(widths[i])) 

당신이 여기 내 소스 코드를보고 싶어 경우

... 마술처럼 10 줄 이상. 나는 그 종류의 대답을 보길 정말로 좋아 하겠지만 (그것은 내가 올바른 것으로 받아 들일 수있는 종류입니다), 이상한 구문을 설명하십시오. 그러나 만약 당신이 단지 기존의 기존 작품에 추가하고 싶다면 나에게도 좋고 더 좋을 것입니다.

답변

0

답변 해 주셔서 감사합니다. 그들은 둘 다 완벽하게 작동합니다. 왜냐하면 저는이 두 가지 노력의 일부를 하나로 통합하기를 원했기 때문에이 답변 만 게시하고 있습니다.

tableData = [['apples', 'oranges', 'cherries', 'banana'], 
      ['Alice', 'Bob', 'Carol', 'David'], 
      ['dogs', 'cats', 'moose', 'goose']] 

#function to get an array of the length of the longest words 
def Widths(tableData): 
    widths = [len(max(column, key=len)) for column in tableData] 
    return(widths) 

#function to print table      
def printTable(tableData): 
    widths = Widths(tableData) 
    for i in range(len(tableData[0])): 
     for j in range(len(tableData)): 
      try: 
       print(tableData[j][i].rjust(widths[j]), end = ' ') 
      except: 
       pass 
     print('') 
0

하위 목록을 zip 세 수 있으므로 세 쌍의 값을 얻을 수 있습니다. 그럼 당신은 (pyformat.info 참조) 공간으로 채워 오른쪽 정렬, 5, 5, 8 폭의 컬럼으로 값을 포맷 할 수 있습니다 : 더 일반적인 대답을

for fruit, person, animal in zip(*tableData): 
    print('{: >8} {: >5} {: >5}'.format(fruit, person, animal)) 

를, 각 컬럼의 최대 폭을 얻을 수 있습니다, 각 너비의 형식 문자열을 만듭니다.

widths = [max(len(value) for value in column) for column in tableData] 
line = ' '.join('{{: >{width}}}'.format(width=width) 
       for width in widths) 
for row in zip(*tableData): 
    print(line.format(*row)) 
+0

와우 ... 그게 내가 익숙하지 않은 구문이지만 배열의 하위 배열 또는 데이터 형식의 수를 알지 못했다고 가정 해 봅시다. 어떻게 처리하겠습니까? – ITJ

+0

스택 오버플로 전체를 고려할 때 다른 질문이 될 수 있습니다. –

+0

내 소스 코드를 보면 배열의 메타 데이터를 직접 사용하지 않았다는 것을 알 수 있습니다. 따라서 수많은 기능 .. – ITJ

0

EDIT에 따라 편집했습니다. 기본 사항을 고수하기 위해이 작업을 수행 할 수 있습니다.

from __future__ import print_function 

tableData = [['apples', 'oranges', 'cherries', 'banana'], 
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']] 
max_width=[] 
for i in tableData: 
    width=[] 
    for obj in range(0,len(i)): 
     width.append(len(i[obj])) #adds the len(i[obj]) 
    max_width.append(max(width)) #appends the length of longest str of the column 

max_height = max(len(i) for i in tableData) #Finds the max height of the array 

for obj in range(0,max_height): #obj is the number of item in a row 
    for index, i in enumerate(tableData): #i a single column in tableData 
     try: #Just in case if one of the rows has fewer item than the rest 
      print ("{0:>{1}}".format(i[obj], max_width[index]+1), end="") #prints it with the proper formatting 
     except: 
      pass 
    print("") 
+0

테이블에서 메타 데이터로 범위 (0,4)를 변경해야하지만이 작업은 확실히 완료됩니다. 프로그램이 어떻게 작업을 수행했는지 추적 할 수 있도록 주석을 추가 할 수 있습니까? – ITJ

+0

@ITJ 의견이 혼란스럽고 다른 표를 지원하도록 범위 (0,4)가 변경되면 죄송합니다. 희망이 도움이 – abccd