Python_9_Codecademy_9_Lists and

2016-04-20  本文已影响27人  张一闻

<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>


课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾


Lists

n = ["ZHANG.Y"]
n = n * 5
print n
Output:
['ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y']
n = [1, 6, 9]
n[1] = n[1] * 3
print n

Output:
[1, 18, 9]

n = [1, 6, 9]
n.append(12)
print n

Output:
[1, 6, 9, 12]

n = [1, 6, 9]
x = n.pop(2)
print x
print n

Output:
9
[1, 6]

n = [1, 6, 9]
n.remove(9)
print n

Output:
[1, 6]

n = [1, 6, 9]
del(n[2])
print n

Output:
[1, 6]

print range(8)
print range(1, 8)
print range(1, 8, 2)

Output:
[0, 1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[1, 3, 5, 7]

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print list3

Outpt:
[1, 2, 3, 4, 5, 6]

list_A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in list_A:
    print i

Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

def flatten(my_list):
    results = []
    for i in my_list:
        for item in i:
            results.append(item)
    return results 
print flatten([[1, 2, 3], [1, 3, 5, 7, 9]])

【方法二】

def flatten(my_list):
    results = []
    for i in my_list:
        for number in range(len(i)):
            results.append(i[number])
    return results
print flatten([[1, 2, 3], [1, 3, 5, 7, 9]])

Output:
[1, 2, 3, 1, 3, 5, 7, 9]

my_list = ['ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y', 'ZHANG.Y']
print " <3 ".join(my_list)
Output:
ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y <3 ZHANG.Y

Functions

def addition(a, b):
    return a + b
print addition(1, 2)

Output:
3

def print_first_item(items):
    print items[0]
n = [1, 6, 9]
print_first_item(n)

Output:
1

# 简单方法:
def print_items(items):
    for x in items:
        print x
n = [1, 6, 9] 
print_items(n)
def print_items(items):
    for x in range(len(items)):
        print items[x]  
n = [1, 6, 9] 
print_items(n)

Output:
1
6
9

def triple_list(my_list):
    for x in range(len(my_list)):
        my_list[x] = my_list[x] * 3
    return my_list
n = [1, 6, 9] 
# 比较
triple_list(n)
print n
print triple_list(n)

Output:
[3, 18, 27]
[9, 54, 81]

上一篇 下一篇

猜你喜欢

热点阅读