简体   繁体   中英

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

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM