0

A.

Can somebody explain what this section does in this code (http://codepad.org/SyWLTfqs)?

class_names = [w.capitalize() for w in
               random.sample(WORDS, snippet.count("###"))]

Where does the "w" come from? Where does the function capitalize() come from?



3
  • 1
    Read about list comprehensions to tell where w comes from. Commented Sep 23, 2012 at 4:08
  • 1
    capitilize() is a method of all string objects. Commented Sep 23, 2012 at 4:08
  • Thanks. I have more questions: Commented Sep 30, 2012 at 12:47

3 Answers 3

1

Firstly, note that random.sample(input, length) returns a list of length snippet.count("###") of the values of WORDS in random order, and capitalize is a method of the String class.
If WORDS is an array of strings, that means w would be assigned to each string at random, applied the method capitalize(), and then put into a list as indicated by the brackets

Sign up to request clarification or add additional context in comments.

Comments

1

It's a list comprehension, iterating over a bunch of strings and calling them w, then calling .capitalize() on them. So class_names is a list of N capitalized randomly selected words from WORDS, where N is the number of occurrences of "###" in snippet.

1 Comment

Removed my answer, yours is better (and you're right about my example). I'm not new to python, but list comprehensions is not something I'm entirely familiar with.
0

capitize() is a Python builtin string function that capitalizes the value in the variable w; a user doesn't have to create it http://docs.python.org/library/string.html.
Basically, there's an iteration within that list variable, and the value in each iteration is assigned to the w.

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.