我的Dicts列表
[
{'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 :(得分: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}]
答案 1 :(得分: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}]
答案 2 :(得分: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}]