2013-07-06 32 views
1

我的目錄的Python類型的字典的迭代列表和創建類型的字典新

[ 
    {'town':'A', 'x':12, 'y':13}, 
    {'town':'B', 'x':100, 'y':43}, 
    {'town':'C', 'x':19, 'y':5} 
] 

我的出發點是:

x = 2 
Y =3 

我最大射程:

mxr = 30 

我的功能:

def calculateRange (x1, x2, y1, y2): 
    squareNumber = math.sqrt(math.pow ((x1-x2),2) + math.pow((y1-y2),2)) 
    return round(squareNumber, 1) 

如何循環訪問我的名單,並在新的列表推送數據和我的函數的結果,如果calculateRange <的結果=我的最大範圍

我想有最後:

[ 
    {'town':'A', 'x':12, 'y':13, 'r':someting }, 
    {'town':'C', 'x':19, 'y':5, 'r':someting} 
] 
+0

該函數不是Python。 –

+0

@RafeKettler好吧,我剛剛更改了語法 – OlZ

+0

沒有'math.round()'函數。你的意思是內置'round()'而不是? –

回答

1

只需使用一個循環:

for entry in inputlist: 
    entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y'])) 

字典是可變的,增加一個關鍵是體現在字典中的所有引用。

演示:

>>> import math 
>>> def calculateRange (x1, x2, y1, y2): 
... squareNumber = math.sqrt(math.pow ((x1-x2),2) + math.pow((y1-y2),2)) 
... return round(squareNumber, 1) 
... 
>>> x = 2 
>>> y = 3 
>>> mxr = 30 
>>> inputlist = [ 
... {'town':'A', 'x':12, 'y':13}, 
... {'town':'B', 'x':100, 'y':43}, 
... {'town':'C', 'x':19, 'y':5} 
... ] 
>>> for entry in inputlist: 
...  entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y'])) 
... 
>>> inputlist 
[{'town': 'A', 'x': 12, 'r': 14.1, 'y': 13}, {'town': 'B', 'x': 100, 'r': 30, 'y': 43}, {'town': 'C', 'x': 19, 'r': 17.1, 'y': 5}] 
+0

好吧,沒辦法考慮最大範圍? – OlZ

+0

@OlZ:只需選擇函數的最小'mxr'值和輸出即可。更新以做到這一點。 –

+0

@OlZ你仍然可以使用列表理解過濾列表。 –

1

我猜你正在尋找的東西是這樣的:

>>> lis = [       
    {'town':'A', 'x':12, 'y':13}, 
    {'town':'B', 'x':100, 'y':43}, 
    {'town':'C', 'x':19, 'y':5} 
] 
>>> x = 2 
>>> y = 3 
for dic in lis: 
    r = calculate(x,y,dic['x'],dic['y']) 
    dic['r'] = r 
...  
>>> lis = [x for x in lis if x['r'] <= mxr] 
>>> lis 
[{'y': 13, 'x': 12, 'town': 'A', 'r': 14.142135623730951}, {'y': 5, 'x': 19, 'town': 'C', 'r': 17.11724276862369}] 
0

這是你想要的嗎?

L = [{'town':'A', 'x':12, 'y':13},{'town':'B', 'x':100, 'y':43},{'town':'C', 'x':19, 'y':5}] 
X, Y = 2, 3 
mxr = 30 

def calculateRange(x1, x2, y1, y2): 
    return round(((x1-x2)**2 + (y1-y2)**2)**.5, 1) 

R = [] 

for e in L: 
    r = calculateRange(e['x'], X, e['y'], Y) 
    if r <= mxr: 
    e['r'] = r 
    R.append(e) 

print R 
# [{'town': 'A', 'x': 12, 'r': 14.1, 'y': 13}, {'town': 'C', 'x': 19, 'r': 17.1, 'y': 5}]