1

我的字典列表

[
   {'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}
]
4

3 回答 3

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}]
于 2013-07-06T16:52:12.003 回答
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}]
于 2013-07-06T17:04:06.213 回答
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}]
于 2013-07-06T17:09:37.727 回答