mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-12 09:44:24 +02:00
Incorporated feedback, and pulled in changes from the master trunk.
This commit is contained in:
@@ -173,6 +173,9 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
|
|||||||
# Examine the length with len
|
# Examine the length with len
|
||||||
len(li) #=> 6
|
len(li) #=> 6
|
||||||
|
|
||||||
|
# Note: lists can contain arbitrary values
|
||||||
|
li2 = [1, "Hello", [[], "Hi", 5,]]
|
||||||
|
|
||||||
# Tuples are like lists but are immutable.
|
# Tuples are like lists but are immutable.
|
||||||
tup = (1, 2, 3)
|
tup = (1, 2, 3)
|
||||||
tup[0] #=> 1
|
tup[0] #=> 1
|
||||||
@@ -376,6 +379,8 @@ add_10(3) #=> 13
|
|||||||
|
|
||||||
# There are also anonymous functions
|
# There are also anonymous functions
|
||||||
(lambda x: x > 2)(3) #=> True
|
(lambda x: x > 2)(3) #=> True
|
||||||
|
rectangle_area = lambda a, b: a * b
|
||||||
|
print rectangle_area(3, 4) #=> 12
|
||||||
|
|
||||||
# There are built-in higher order functions
|
# There are built-in higher order functions
|
||||||
map(add_10, [1,2,3]) #=> [11, 12, 13]
|
map(add_10, [1,2,3]) #=> [11, 12, 13]
|
||||||
@@ -385,6 +390,9 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
|
|||||||
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
|
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
|
||||||
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
|
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
|
||||||
|
|
||||||
|
# You can also use dictionary comprehensions
|
||||||
|
{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13}
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
## 5. Classes
|
## 5. Classes
|
||||||
####################################################
|
####################################################
|
||||||
@@ -400,7 +408,8 @@ class Human(object):
|
|||||||
# Assign the argument to the instance's name attribute
|
# Assign the argument to the instance's name attribute
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
||||||
# An instance method. All methods take self as the first argument
|
# An instance method. All methods take self as the first argument,
|
||||||
|
# which refers to the instance of this class
|
||||||
def say(self, msg):
|
def say(self, msg):
|
||||||
return "%s: %s" % (self.name, msg)
|
return "%s: %s" % (self.name, msg)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user