Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Data Science
#1
Hello everybody, i have some questions regarding the following code in python:

localWinds = {name: site.local_wind(x_i=site.initial_position[:,0], # x position

                                    y_i = site.initial_position[:,1], # y position
                                    h_i=site.initial_position[:,0]*0+70, # height
                                    ws=None, # defaults to 3,4,..,25
                                    wd=None, # defaults to 0,1,...,360
                                    ) for name, site in sites.items()}
firstly I want to know what is the function of {name:.....}? why we used it here?
secondly, for in the last line means that we set these values x_i.... for the variable of name?
lastly, site in sites.items means every item in sites will be placed in variable: Site ??
buran write Oct-14-2021, 06:51 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
This is called dict comprehension. Usually it will result in shorter (more compact) code, but in this case, with long call of site.local_wind it is better (for readability) to use regular loop to fill in the dict.
It is equivalent to following regular loop:

localWinds = {}
for name, site in sites.items():
    localWinds[name] = site.local_wind(x_i=site.initial_position[:,0], # x position
                                       y_i = site.initial_position[:,1], # y position
                                       h_i=site.initial_position[:,0]*0+70, # height
                                       ws=None, # defaults to 3,4,..,25
                                       wd=None, # defaults to 0,1,...,360
                                       ) 
basically sites is a dict and for sites.items() will yield individual (key, value) pairs. Each tuple will be unpacked into name and site. a new dict is created with key=name and value = the result of site.local_wind() called with respective arguments
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python issue - Data science - Help is needed yovel 2 2,016 Jul-29-2021, 04:27 PM
Last Post: yovel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020