0

I am a beginner in Python and kindly I have a question: Given the following:

np.asarray([self.simulate(c) for c in challenges])

I want to break it down to look familiar in the traditional coding way. Can I say it is equivalent to:

for c in challenges:
    y = self.simulate(c)
    y = np.asarray[y]

Thank you.

2
  • 2
    no, you're losing the cumulative effect, and y is overwritten at each iteration. create a list and append to it. Then build your array. Commented Jul 20, 2017 at 17:22
  • you will want to predeclare y as a list before the loop and do y.append(self.simulate....) and after the loop for np.asarray(y) Commented Jul 20, 2017 at 17:23

2 Answers 2

4

It's not called "pythonic looping", but list comprehension.

The equivalent would be:

items = []
for c in challenges:
    items.append(self.simulate(c))

nparr = np.asarray(items)
Sign up to request clarification or add additional context in comments.

Comments

1

The problem with your method is that you're are not building a list, such as this list comprehension does. Rather, you are simply indexing one item from np.asarray, and never saving the value. Furthermore, you don't even want to be indexing np.asarray, you want to pass a list to its constructor.

You need to create a temporary list to hold the return value of self.simulate(c) on each iteration of challenges and pass that list to np.asarray:

temp = []
for c in challenges:
    temp.append(self.simulate(c))
array = np.asarray(temp)

Also, just to let you know, the "pythonic loop" you're referring to is usually called a list comprehension. "Pythonic" is just a name us Python community members use to describe something that is idiomatic to the Python language and its ideals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.