[英]Python iterate list of dicts and create a new one
My list of Dicts 我的字典清单
[
{'town':'A', 'x':12, 'y':13},
{'town':'B', 'x':100, 'y':43},
{'town':'C', 'x':19, 'y':5}
]
My starting point is: 我的出发点是:
x = 2
Y =3
My maximum range: 我的最大范围:
mxr = 30
My function: 我的功能:
def calculateRange (x1, x2, y1, y2):
squareNumber = math.sqrt(math.pow ((x1-x2),2) + math.pow((y1-y2),2))
return round(squareNumber, 1)
How to iterate my list and push data and the result of my function in a new list if the result of calculateRange <= to my maximum range 如果calculateRange的结果<=到我的最大范围,如何迭代我的列表并将数据和函数的结果推送到新列表中
I would like to have finally: 我最后想拥有:
[
{'town':'A', 'x':12, 'y':13, 'r':someting },
{'town':'C', 'x':19, 'y':5, 'r':someting}
]
Just use a loop: 只需使用一个循环:
for entry in inputlist:
entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y']))
Dictionaries are mutable, adding a key is reflected in all references to the dictionary. 字典是可变的,添加键反映在字典的所有引用中。
Demo: 演示:
>>> 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}]
I guess you're looking for something like this: 我想您正在寻找这样的东西:
>>> 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}]
Is this what you want? 这是你想要的吗?
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.