kaggle之Python基础

Python基础 完结



前言

kaggle先导课程


一、语法 赋值

1.课程内容

spam_amount = 0
print(spam_amount)

# Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
spam_amount = spam_amount + 4

if spam_amount > 0:
    print("But I don't want ANY spam!")

viking_song = "Spam " * spam_amount
print(viking_song)

分析:

  1. spam_amount = 0
    在声明变量前,不需要告知该变量类型,且声明后也可以直接改变其类型
  2. print(spam_amount)
    print是Python的函数,在使用Python函数时,只需 函数名(参数)
  3. ** # Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam) **
    Python中注释符:#
  4. if spam_amount > 0:
    print(“But I don’t want ANY spam!”)

    强调行首缩进,并利用行首缩进划分代码块

2.作业总结

  1. 运算操作
    arithmetic operations
  2. 运算优先级
    括号>指数>乘除>加减

二、使用函数 定义函数

1. 使用help函数

help(round)
展示两条信息:
1. 函数头,包括参数
2. 函数功能的简短描述

2. 定义函数

基础格式:

	def 函数名 :
		函数体
		return 返回值

docstring
三重引号内部,可以有多行注释信息;
紧跟在函数名下,通常由简单的文字描述和函数示例组成
默认参数

	def greet(who="Colin"):
    	print("Hello,", who) 
	greet()
	greet(who="Kaggle")

将函数作为另一个函数的参数

	def mult_by_five(x):
    	return 5 * x

	def call(fn, arg):
    	"""Call fn on arg"""
    	return fn(arg)

	def squared_call(fn, arg):
    	"""Call fn on the result of calling fn on arg"""
    	return fn(fn(arg))

	print(
    	call(mult_by_five, 1),
    	squared_call(mult_by_five, 1), 
   	 sep='\n', # '\n' is the newline character - it starts a new line)

三、布尔和条件

1. 布尔

赋值
既可以直接赋值True/False,也可以用布尔操作式赋值
Comparison Operations
运算符优先级

  1. and > or
    example:
    True or True and False
    值为True
  2. 在复杂and、or、not运算中,推荐使用括号

2. 条件

if - elif - else
用:表示条件语句的结束,用行首缩进划分代码块

3. Boolean 转换

数值转换
int ( )、 float( )
布尔转换

  1. 除了0,其他所有的数都可被当作True
  2. 除了空白字符串,其他所有的字符串都可被当作True
  3. 通常空的序列(例如字符串、列表以及与字符串和列表相似的对象)都会被当作False

4. 习题内容

  1. 布尔运算符歧义未完全理解
    have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
    
    歧义原因:not rain_level > 0 and is_workday
    本意:not (rain_level > 0 and is_workday)
    实际:(not (rain_level > 0)) and is_workday
  2. 布尔转化为整数
    可以使用int()将布尔类型转化为整数类型,True为1,False为0
    但是,当对布尔类型数据进行运算操作时,Python会自动将其变为数据类型

四、列表

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

1. 列表的定义

成员可以是数值、字符串、列表和混合元素

my_favourite_things = [32, 'raindrops on roses', help]

2. 下标

访问单个元素
列表名[下标]

3. 切片

列表名[切片起始下标:切片结束下标后一位]
例如:前三位元素的切片为:

planet[ 0 : 3 ]

并且起始下标和结束下标是可选择的,默认起始值为第一个,默认结束值为最后一个元素
切片示例

示例1:

# All the planets except the first and last
planets[1:-1]
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']

示例2:

# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']

4. 修改列表

planets[3] = 'Malacandra'
planets[:3] = ['Mur', 'Vee', 'Ur']

5. 列表相关函数

  1. len()给出列表长度
  2. sorted()给出一个有序列表
  3. sum()求和
  4. max() min()最大 最小元素

6. 列表内置方法

  1. 列表名.append('元素')将元素添加至列表尾部
  2. 列表名.pop()删除列表中最后一个元素并将其返回
  3. 列表名.index('元素')返回元素在列表中的下标,当列表中不存在该元素时,会报错
  4. "元素" in 列表名当该元素在列表中时,返回True;反之返回False

五、元组

1.与列表仅有两处不同

  1. 元组的创建是用小括号 / 列表的创建是用方括号
  2. 元组内部元素不能被改变

2. 常用作函数返回多值

x = 0.125
x.as_integer_ratio()
(1, 8)

3. 元组中的多返回值可分别给变量赋值

numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
0.125

4. 交换两个变量

a = 1
b = 0
a, b = b, a
print(a, b)

习题相关

  1. 函数返回None:
    1. return
    2. return None
  2. 交换列表中元素
racers[0], racers[-1] = racers[-1], racers[0]
  1. 列表长度
d = [1, 2, 3][1:]
The expression is the same as the list [2, 3], which has length 2.
  1. 错题
    题目:We’re using lists to record people who attended our party and what order they arrived in. For example, the following list represents a party with 7 guests, in which Adela showed up first and Ford was the last to arrive:

party_attendees = [‘Adela’, ‘Fleda’, ‘Owen’, ‘May’, ‘Mona’, ‘Gilbert’, ‘Ford’]
A guest is considered ‘fashionably late’ if they arrived after at least half of the party’s guests. However, they must not be the very last guest (that’s taking it too far). In the above example, Mona and Gilbert are the only guests who were fashionably late.

Complete the function below which takes a list of party attendees as well as a person, and tells us whether that person is fashionably late.
题解

def fashionably_late(arrivals, name):
    order = arrivals.index(name)
    return order >= len(arrivals) / 2 and order != len(arrivals) - 1

错解

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """
    length = len(arrivals)
    if length % 2 == 0:
        start = (length / 2)
    else:
        start = ((length // 2) + 1)
    fashionably_late_name = arrivals[start : -1]
    return name in fashionably_late_name

报错信息:

TypeError: slice indices must be integers or None or have an __index__ method

订正

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """
    length = len(arrivals)
    if length % 2 == 0:
        start = int(length / 2)
    else:
        start = int((length // 2) + 1)
    print(start)
    fashionably_late_name = arrivals[start : -1]
    return name in fashionably_late_name

六、 循环

1. 循环定义

1.1 for循环

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
    print(planet, end=' ') # print all on same line

格式:for 变量名 in 集合名

  1. 规定了所使用的变量名称以及循环变量的集合
  2. 集合也可以是元组和字符串
  3. **range()**提供数字序列,有效用来循环遍历。例如:
for i in range(5):
    print("Doing important work. i =", i)

1.2 while循环

i = 0
while i < 10:
    print(i, end=' ')
    i += 1 # increase the value of i by 1

七、列表推导

1. 与for循环相关

示例1:

squares = [n**2 for n in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

示例二

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']

示例三:
左边的表达式不一定需要包含循环变量,虽然这种表达方式不实用

[32 for planet in planets]
[32, 32, 32, 32, 32, 32, 32, 32]

示例四:结合min,max,sun将极大程度减少代码行数
常规写法:

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

使用列表推导:

def count_negatives(nums):
    return len([num for num in nums if num < 0])

结合sum:

def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

2. 习题

1. 结合any函数的列表推导

def has_lucky_number(nums):
    return any([num % 7 == 0 for num in nums])

2. 错题

Implement a function that reproduces this behaviour, returning a list of booleans corresponding to whether the corresponding element is greater than n.

def elementwise_greater_than(L, thresh):
    res = []
    for ele in L:
        res.append(ele > thresh)
    return res
# the list comprehension version
def elementwise_greater_than(L, thresh): 
    return [ele > thresh for ele in L]

3. 错题

题目: Given a list of meals served over some period of time, return True if the same meal has ever been served two days in a row, and False otherwise.
错解1:

def menu_is_boring(meals):
	for meal in meals:
        index = meals.index(meal)
        if(meals[index+1] == meal):
            return True
    return False
# IndexError: list index out of range

错解2:

def menu_is_boring(meals):
	for i in len(meals):
        for j in (len(meals[i])-1):
            if(meals[j] == meals[(j+1)]):
                return True
    return False
# TypeError: 'int' object is not iterable

错解3:

def menu_is_boring(meals):
	for i in range(len(meals)):
        for j in range(len(meals[i])-1):
            if(meals[j] == meals[j+1]):
                return True
    return False
# Incorrect: When calling your function with arguments [['Egg', 'Spam']], Python raised the following exception... 
# IndexError: list index out of range
# 错误原因:被报错信息里的arguments [['Egg', 'Spam']]迷惑,以为是嵌套列表

答案:

def menu_is_boring(meals):
    # Iterate over all indices of the list, except the last one
    for i in range(len(meals)-1):
        if meals[i] == meals[i+1]:
            return True
    return False
# 总结:range(len(meals))将会给出meals中所有的下标

4. 好题

def estimate_average_slot_payout(n_runs):
	return ((sum([play_slot_machine() for i in range(n_runs)]) - n_runs) / n_runs)
print(estimate_average_slot_payout(10000000))
# 0.0256615

答案:

def estimate_average_slot_payout(n_runs):
    # Play slot machine n_runs times, calculate payout of each
    payouts = [play_slot_machine()-1 for i in range(n_runs)]
    # Calculate the average value
    avg_payout = sum(payouts) / n_runs
    return avg_payout
estimate_average_slot_payout(10000000)
# This should return an answer close to 0.025!

八、字符串

1. 相关语法

  1. 单引号和双引号等价,当内容中包含单引号时,建议外部使用双引号
    例如:
x = 'Pluto is a planet'
y = "Pluto is a planet"
x == y
#True
print("Pluto's a planet!")
print('My dog is named "Pluto"')
# Pluto's a planet!
# My dog is named "Pluto"
  1. 转义字符举例
    转移字符
  2. 三重引号可使字符串中包含真正的换行
    示例:
triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello
# hello
# world
# True
  1. print()默认在当前输出完成后添加换行,除非我们对end元素赋值
    与输出函数相关的元素还有
    示例:
print("hello")
print("world")
print("hello", end='')
print("pluto", end='')

2. 字符串作为序列

相同操作:下标、切片、长度、作为循环变量集合
例如:

# Indexing
planet = 'Pluto'
planet[0]
# Slicing
planet[-3:]
# How long is this string?
len(planet)
# Yes, we can even loop over them
[char+'! ' for char in planet]

*不同操作:不能修改字符串,也不能使用append方法
例如:

planet[0] = 'B'
# planet.append doesn't work either

3. 字符串相关函数

  1. upper()将字符串内容全部转化为大写
  2. lower()将字符串内容全部转化为小写
  3. index('元素')在字符串中搜索所给元素是否在字符串中,并返回元素的第一个下标
  4. startswith(‘元素’) / endswith(‘元素’)判断字符串是否以所给元素开头/结尾
  5. split()将字符串划分为更小字符串的列表,默认划分值为空格;
words = claim.split()
words
# ['Pluto', 'is', 'a', 'planet!']

也可以设置划分值:

datestr = '1956-01-31'
year, month, day = datestr.split('-')
  1. join()将列表中的字符串连接为一整个字符串
'/'.join([month, day, year])
# '01/31/1956'
' 👏 '.join([word.upper() for word in words])
# 'PLUTO 👏 IS 👏 A 👏 PLANET!'
  1. format()重点: 串联字符串
    当不使用format函数串联字符串时:
planet + ", you'll always be the " + str(position) + "th planet to me."

其中,需要使用➕,且当插入元素为非字符串元素时,需要用str()将其转换为字符串元素
当使用format()函数串联字符串时:

"{}, you'll always be the {}th planet to me.".format(planet, position)

只需要将{}放在需要插入元素的位置即可,在后续的format()中写入需要插入到元素,其中,当需要插入的元素为非字符串元素时,format会自动将其转化并完成插入操作
format()其他作用:

pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
# 2 decimal points   3 decimal points, format as percent     separate with commas
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(planet, pluto_mass, pluto_mass / earth_mass, population)
# "Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."

# Referring to format() arguments by index, starting from 0
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)

4. 习题

习题1:

题目: Given a string, it should return whether or not that string represents a valid zip code. For our purposes, a valid zip code is any string consisting of exactly 5 digits.
答案:

def is_valid_zip(zip_code):
    return len(zip_code) == 5 and zip_code.isdigit()

解析:
1.help(len):
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
2. help(str.isdigit)
Help on method_descriptor:
isdigit(self, /)
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.

习题2:

题目:
A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles.
Your function should meet the following criteria:

  • Do not include documents where the keyword string shows up only as a part of a larger word. For example, if she were looking for the keyword “closed”, you would not include the string “enclosed.”
  • She does not want you to distinguish upper case from lower case letters. So the phrase “Closed the case.” would be included when the keyword is “closed
  • Do not let periods or commas affect what is matched. “It is closed.” would be included when the keyword is “closed”. But you can assume there are no other types of punctuation.
    错解:
def word_search(doc_list, keyword):
	ret = []
    for i in range(len(doc_list)):
        doc = doc_list[i].lower()
        words = doc.split()
        if keyword in words:
            ret.append(i)
    return ret
# Incorrect: Expected return value of [1] given doc_list=['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], keyword='car', but got [] instead.

答案:

def word_search(doc_list, keyword):
    # list to hold the indices of matching documents
    indices = [] 
    # Iterate through the indices (i) and elements (doc) of documents
    for i, doc in enumerate(doc_list):
        # Split the string doc into a list of words (according to whitespace)
        tokens = doc.split()
        # Make a transformed list where we 'normalize' each word to facilitate matching.
        # Periods and commas are removed from the end of each word, and it's set to all lowercase.
        normalized = [token.rstrip('.,').lower() for token in tokens]
        # Is there a match? If so, update the list of matching indices.
        if keyword.lower() in normalized:
            indices.append(i)
    return indices

解析:

  1. help(enumerate):
    Help on class enumerate in module builtins:
    class enumerate(object)
    | enumerate(iterable, start=0)
    |
    | Return an enumerate object.
    |
    | iterable
    | an object supporting iteration
    |
    | The enumerate object yields pairs containing a count (from start, which
    | defaults to zero) and a value yielded by the iterable argument.
    |
    | enumerate is useful for obtaining an indexed list:
    | (0, seq[0]), (1, seq[1]), (2, seq[2]), …
    |
    | Methods defined here:
    |
    | getattribute(self, name, /)
    | Return getattr(self, name).
    |
    | iter(self, /)
    | Implement iter(self).
    |
    | next(self, /)
    | Implement next(self).
    |
    | reduce(…)
    | Return state information for pickling.
    |
    | ----------------------------------------------------------------------
    | Static methods defined here:
    |
    | new(*args, **kwargs) from builtins.type
    | Create and return a new object. See help(type) for accurate signature.
  2. help(str.strip):
    Help on method_descriptor:
    strip(self, chars=None, /)
    Return a copy of the string with leading and trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.
  3. help(str.split):
    Help on method_descriptor:
    split(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.
    sep
    The delimiter according which to split the string.
    None (the default value) means split according to any whitespace,and discard empty strings from the result.
    maxsplit
    Maximum number of splits to do.
    -1 (the default value) means no limit.

九、字典

1. 键值对

numbers = {'one':1, 'two':2, 'three':3}

numbers['one']
# 1

numbers['eleven'] = 11
numbers
# {'one': 1, 'two': 2, 'three': 3, 'eleven': 11}

numbers['one'] = 'Pluto'
numbers
# {'one': 'Pluto', 'two': 2, 'three': 3, 'eleven': 11}

2. 字典推导

语法和列表推导一致

  1. 与for循环有关的推导
    结合字典循环和字符串作为列表对待
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets}
planet_to_initial

其中,in可判断所给元素是否在字典中为键

'Saturn' in planet_to_initial
# True

for循环也是建立在字典的键之上

for k in numbers:
    print("{} = {}".format(k, numbers[k]))
# one = Pluto
# two = 2
# three = 3
# eleven = 11
  1. dict.keys() dict.values()获取字典中的所有键/值
# Get all the initials, sort them alphabetically, and put them in a space-separated string.
' '.join(sorted(planet_to_initial.values()))
# 'E J M M N S U V'
  1. dict.items()同时迭代键值对
for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial))
#    Mercury begins with "M"
#      Venus begins with "V"
#      Earth begins with "E"
#       Mars begins with "M"
#    Jupiter begins with "J"
#     Saturn begins with "S"
#     Uranus begins with "U"
#    Neptune begins with "N"

3. 习题

与八.4.习题2相关
Now the researcher wants to supply multiple keywords to search for. Complete the function below to help her.
(You’re encouraged to use the word_search function you just wrote when implementing this function. Reusing code in this way makes your programs more robust and readable - and it saves typing!)

def multi_word_search(doc_list, keywords):
	"""
    信息:所给参数都是列表
    第一步:创建字典
        键:所给关键字;值:列表(关键字在列表中的下标组成)
    第二步:遍历关键字链表
        将关键字列表中的每一个元素都作为参数调用word_search function
        将word_search function的返回值作为 该关键值在字典中所对应的值
    """
    # 利用字典中的”字典推导“创建字典
    ret = {key:[] for key in keywords}
    for i in keywords:
        ret[i] = word_search(doc_list, i)
    return ret

十、imports

1. 举例:

import math
rint("It's math! It has type {}".format(type(math)))
# It's math! It has type <class 'module'>

print(dir(math)) # 查看该函数中的变量
"""
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
"""

print("pi to 4 significant digits = {:.4}".format(math.pi))
# pi to 4 significant digits = 3.142

math.log(32, 2)
# 5.0

2. 其他调用语句:

import math as mt
mt.pi
# 3.141592653589793

3. import * 示例

from math import *
print(pi, log(32, 2))
# 3.141592653589793 5.0

4. import * 错误示例

from math import *
from numpy import *
print(pi, log(32, 2))
# TypeError: return arrays must be of ArrayType

错误原因: math和numpy都有log函数,后导入的numpy中的log函数重写 math中的log函数
改正: 仅导入需要的部分

from math import log, pi
from numpy import asarray

5. 子模块 submodules

import numpy
print("numpy.random is a", type(numpy.random))
print("it contains names such as...",
      dir(numpy.random)[-15:]
     )
"""
numpy.random is a <class 'module'>
it contains names such as... ['seed', 'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'test', 'triangular', 'uniform', 'vonmises', 'wald', 'weibull', 'zipf']
"""
# Roll 10 dice
rolls = numpy.random.randint(low=1, high=6, size=10)
rolls
# array([4, 2, 4, 5, 3, 1, 4, 2, 5, 1])

6. work with strange types

1. type()

** what is this thing?**

type(rolls)
# numpy.ndarray

2. dir()

what can I do with it?

print(dir(rolls))
"""
['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']
"""
# If I want the average roll, the "mean" method looks promising...
rolls.mean()
# 3.1

# Or maybe I just want to turn the array into a list, in which case I can use "tolist"
rolls.tolist()
# [4, 2, 4, 5, 3, 1, 4, 2, 5, 1]

3. help()

tell me more

# That "ravel" attribute sounds interesting. I'm a big classical music fan.
help(rolls.ravel)
"""
Help on built-in function ravel:

ravel(...) method of numpy.ndarray instance
    a.ravel([order])
    
    Return a flattened array.
    
    Refer to `numpy.ravel` for full documentation.
    
    See Also
    --------
    numpy.ravel : equivalent function
    
    ndarray.flat : a flat iterator on the array.

"""

7. 运算符重载

[3, 4, 1, 2, 2, 1] + 10
# TypeError: can only concatenate list (not "int") to list

rolls + 10
# array([14, 12, 14, 15, 13, 11, 14, 12, 15, 11])
#  The designers of numpy arrays went a different way (adding the number to each element of the array).

与numpy有关的一些运算符:

# At which indices are the dice less than or equal to 3?
rolls <= 3
# array([False, True, False, False, True, True, False, True, False, True])
xlist = [[1,2,3],[2,4,6],]
# Create a 2-dimensional array
x = numpy.asarray(xlist)
print("xlist = {}\nx =\n{}".format(xlist, x))
"""
xlist = [[1, 2, 3], [2, 4, 6]]
x =
[[1 2 3]
 [2 4 6]]
"""
# Get the last element of the second row of our numpy array
x[1,-1]
# 6

# Get the last element of the second sublist of our nested list?
xlist[1,-1]
# TypeError: list indices must be integers or slices, not tuple

8. 1 + 1 != 2

tensorflow相关

9. 习题

1. 习题一

  1. Add the title “Results of 500 slot machine pulls”
  2. Make the y-axis start at 0.
  3. Add the label “Balance” to the y-axis
  4. format the numbers on the y-axis so they look like dollar amounts? e.g. $200 instead of just 200.
    答案:
def prettify_graph(graph):
    graph.set_title("Results of 500 slot machine pulls")
    # Make the y-axis begin at 0
    graph.set_ylim(bottom=0)
    # Label the y-axis
    graph.set_ylabel("Balance")
    # Bonus: format the numbers on the y-axis as dollar amounts
    # An array of the values displayed on the y-axis (150, 175, 200, etc.)
    ticks = graph.get_yticks()
    # Format those values into strings beginning with dollar sign
    new_labels = ['${}'.format(int(amt)) for amt in ticks]
    # Set the new labels
    graph.set_yticklabels(new_labels)

解析:

type(graph)
# matplotlib.axes._subplots.AxesSubplot

help(graph.set_title)
"""
Help on method set_title in module matplotlib.axes._axes:
set_title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set a title for the Axes.
    Set one of the three available Axes titles. The available titles
    are positioned above the Axes in the center, flush with the left
    edge, and flush with the right edge.
  
    Parameters
    ----------
    label : str
        Text to use for the title
    
    fontdict : dict
        A dictionary controlling the appearance of the title text,
        the default *fontdict* is::
    
           {'fontsize': rcParams['axes.titlesize'],
            'fontweight': rcParams['axes.titleweight'],
            'color': rcParams['axes.titlecolor'],
            'verticalalignment': 'baseline',
            'horizontalalignment': loc}
    
    loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`
        Which title to set.
    
    y : float, default: :rc:`axes.titley`
        Vertical Axes loation for the title (1.0 is the top).  If
        None (the default), y is determined automatically to avoid
        decorators on the Axes.
    
    pad : float, default: :rc:`axes.titlepad`
        The offset of the title from the top of the Axes, in points.
    
    Returns
    -------
    `.Text`
        The matplotlib text instance representing the title
    
    Other Parameters
    ----------------
    **kwargs : `.Text` properties
        Other keyword arguments are text properties, see `.Text` for a list
        of valid text properties.
"""

help(graph.set_ylim)
"""
Help on method set_ylim in module matplotlib.axes._base:

set_ylim(bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the y-axis view limits.
    
    Parameters
    ----------
    bottom : float, optional
        The bottom ylim in data coordinates. Passing *None* leaves the
        limit unchanged.
    
        The bottom and top ylims may also be passed as the tuple
        (*bottom*, *top*) as the first positional argument (or as
        the *bottom* keyword argument).
    
        .. ACCEPTS: (bottom: float, top: float)
    
    top : float, optional
        The top ylim in data coordinates. Passing *None* leaves the
        limit unchanged.
    
    emit : bool, default: True
        Whether to notify observers of limit change.
    
    auto : bool or None, default: False
        Whether to turn on autoscaling of the y-axis. *True* turns on,
        *False* turns off, *None* leaves unchanged.
    
    ymin, ymax : float, optional
        They are equivalent to bottom and top respectively,
        and it is an error to pass both *ymin* and *bottom* or
        *ymax* and *top*.
    
    Returns
    -------
    bottom, top : (float, float)
        The new y-axis limits in data coordinates.
    
    See Also
    --------
    get_ylim
    set_ybound, get_ybound
    invert_yaxis, yaxis_inverted
    
    Notes
    -----
    The *bottom* value may be greater than the *top* value, in which
    case the y-axis values will decrease from *bottom* to *top*.
    
    Examples
    --------
    >>> set_ylim(bottom, top)
    >>> set_ylim((bottom, top))
    >>> bottom, top = set_ylim(bottom, top)
    
    One limit may be left unchanged.
    
    >>> set_ylim(top=top_lim)
    
    Limits may be passed in reverse order to flip the direction of
    the y-axis. For example, suppose ``y`` represents depth of the
    ocean in m. The y-axis limits might be set like the following
    so 5000 m depth is at the bottom of the plot and the surface,
    0 m, is at the top.
    
    >>> set_ylim(5000, 0)
"""
help(graph.set_ylabel)
"""
Help on method set_ylabel in module matplotlib.axes._base:

set_ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the label for the y-axis.
    
    Parameters
    ----------
    ylabel : str
        The label text.
    
    labelpad : float, default: :rc:`axes.labelpad`
        Spacing in points from the Axes bounding box including ticks
        and tick labels.  If None, the previous value is left as is.
    
    loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
        The label position. This is a high-level alternative for passing
        parameters *y* and *horizontalalignment*.
    
    Other Parameters
    ----------------
    **kwargs : `.Text` properties
        `.Text` properties control the appearance of the label.
    
    See Also
    --------
    text : Documents the properties supported by `.Text`.
"""
help(graph.set_xticklabels)
"""
Help on method set_xticklabels in module matplotlib.axes._base:

set_xticklabels(labels, *, fontdict=None, minor=False, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the xaxis' labels with list of string labels.
    
    .. warning::
        This method should only be used after fixing the tick positions
        using `.Axes.set_xticks`. Otherwise, the labels may end up in
        unexpected positions.
    
    Parameters
    ----------
    labels : list of str
        The label texts.
    
    fontdict : dict, optional
        A dictionary controlling the appearance of the ticklabels.
        The default *fontdict* is::
    
           {'fontsize': rcParams['axes.titlesize'],
            'fontweight': rcParams['axes.titleweight'],
            'verticalalignment': 'baseline',
            'horizontalalignment': loc}
    
    minor : bool, default: False
        Whether to set the minor ticklabels rather than the major ones.
    
    Returns
    -------
    list of `.Text`
        The labels.
    
    Other Parameters
    ----------------
    **kwargs : `~.text.Text` properties.
"""
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值