2014-04-26 2 views
3

나는 좌표 쌍과 정수가 포함 된 사전을 가지고 있습니다. 첫 번째 문제는 일부 포인트가 부정적이라는 것입니다.배열에 대한 점과 값의 사전

{(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4} 

to 

+---+---+---+ 
| 0 | 0 | 4 | 
+---+---+---+ 
| 0 | 1 | 0 | 
+---+---+---+ 
| 2 | 0 | 3 | 
+---+---+---+ 

필자는 모든 쌍을 0보다 크게 조정해야하므로 행렬과 행 쌍으로 사용할 수 있다고 생각합니다. 삽입은 다음입니다. 나는 파이썬이 단지 열거되지 않은 배열을 필요로하므로 행렬이 아닌 중첩 된 목록을 가지고 있다고 믿는다.

+0

귀하의 예는 홀수 경계 (3 × 3가) 그래서 센터는 모호하지 않습니다. 짝수 경계가있는 행렬의 중심을 어떻게 정의합니까? 행렬이 4 x 6이고, 상대 좌표의 중심은 무엇입니까? – dawg

+0

반드시 중앙에 위치시킬 필요는 없습니다. 직교 좌표계에서 점을 이동하여 사분면 1에 모두 올리는 것과 같습니다. –

답변

1

순수 파이썬을 사용하여 :

def solve(d): 

    x_min, y_min = map(min, zip(*d)) 
    x_max, y_max = map(max, zip(*d)) 

    arr = [[0]*(x_max-x_min+1) for _ in xrange(y_max-y_min+1)] 

    for i, y in enumerate(xrange(y_min, y_max+1)): 
     for j, x in enumerate(xrange(x_min, x_max+1)): 
      arr[i][j] = d.get((x, y), 0) 
    return arr[::-1] 

출력 :

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}) 
Out[80]: 
[[0, 0, 4], 
[0, 1, 0], 
[2, 0, 3]] 

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 2):30, (-3, -4):100}) 
Out[82]: 
[[0, 0, 0, 0, 0, 30], 
[0, 0, 0, 0, 4, 0], 
[0, 0, 0, 1, 0, 0], 
[0, 0, 2, 0, 3, 0], 
[0, 0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0, 0], 
[100, 0, 0, 0, 0, 0]] 
+0

'xrange '가 무엇입니까? –

+1

@BenLongo A [기본 제공 함수] (https://docs.python.org/2/library/functions .html # xrange). Python 3을 사용하는 경우를 대비하여 ['range()'] (https://docs.python.org/3/library/functions.html#func-range)를 사용하십시오. –

0
import numpy 
s = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4} 
x = numpy.array([k+(v,) for k,v in s.iteritems()]) 
x[:,0]-=x[:,0].min() 
x[:,1]-=x[:,1].min() 
w = numpy.zeros((x[:,0].max()+1,x[:,1].max()+1)) 
w[x[:,:2].T.tolist()]=x[:,2] 

resut :

>>> w 
array([[ 2., 0., 0.], 
     [ 0., 1., 0.], 
     [ 3., 0., 4.]]) 
0
import numpy as np 


def make_array(data): 
    # In your example row is the second index and col is the first. 
    # Also positive row indexes go in up direction. 
    c, r = np.array(zip(*data.keys())) 

    rows = r.max()-r.min()+1 
    cols = c.max()-c.min()+1 

    result = np.zeros((rows, cols), dtype=int) 

    for k, v in data.iteritems(): 
     # Minus before first index required for 
     # the last row contain 2, 0, 3 in the example. 
     # Also numpy successfully handle negative indexes 
     # and inversion not required 
     result[-k[1]+1, k[0]+1] = v 

    return result 

테스트 케이스 :

data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4} 
print make_array(data) 

결과 : d와

[[0 0 4] 
[0 1 0] 
[2 0 3]] 

예 ifferent 행과 열 수 :

data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 1): 5} 
print make_array(data) 

결과 :

----------- "-First" column 
    |  ----- Second column 
    |  | 
[[0 0 4 5]  <-- First row 
[0 1 0 0]  <-- Zero row 
[2 0 3 0]] <-- "-First" row 
관련 문제