函数定义学习方法

  • 我在写代码的时候一般直接调用写好的包比较多
  • 总是忘记定义函数减少重复代码这个
  • 我觉得还是平时项目看的少,代码写的比较少的原因
  • 解决方法除了看视频做笔记之外,最重要的是自己写啊。
  • 问题不大,勤奋一点即可
  • 嗯,打好基础很重要的
  • 适度记忆

1.Nested functions 嵌套函数

这里不打算写demo,但是想说,一定要明白自己的需求才能写下去

2.匿名函数学习笔记

结构:

lambda 参数 : 表达式

只有一行

# Define echo_word as a lambda function: echo_word
echo_word = (lambda word1, echo: word1 * echo)

# Call echo_word: result
result = echo_word('hey', 5)

# Print result

heyheyheyheyheyhey

map()

这个函数的用法和R里面一样吧

# Create a list of strings: spells
spells = ['protego', 'accio', 'expecto patronum', 'legilimens']

# Use map() to apply a lambda function over spells: shout_spells
shout_spells = map(lambda item: item + '!!!', spells)

# Convert shout_spells to a list: shout_spells_list
shout_spells_list = list(shout_spells)

# Print the result
print(shout_spells_list)

<script.py> output:
    ['protego!!!', 'accio!!!', 'expecto patronum!!!', 'legilimens!!!']

异常处理

  • try块让你可以检测代码块中的错误。
  • except块让你可以处理错误。
  • finally块让你可以执行最终代码,不管try与except块的结果如何,finally块的代码都将执行
    try:
    except
    把出问题的代码放入上述结构中
    进行检验
# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""

    # Initialize an empty dictionary: cols_count
    cols_count = {}

    # Add try block
    try:
        # Extract column from DataFrame: col
        col = df[col_name]
        
        # Iterate over the column in dataframe
        for entry in col:
    
            # If entry is in cols_count, add 1
            if entry in cols_count.keys():
                cols_count[entry] += 1
            # Else add the entry to cols_count, set the value to 1
            else:
                cols_count[entry] = 1
    
        # Return the cols_count dictionary
        return cols_count

    # Add except block
    except:
        'The DataFrame does not have a ' + col_name + ' column.'

# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')

# Print result1
print(result1)

迭代器

iterator
.iter()

# Create a list of strings: flash
flash = ['jay garrick', 'barry allen', 'wally west', 'bart allen']

# Print each list item in flash using a for loop
for person in flash:
    print(person)

# Create an iterator for flash: superhero
superhero = iter(flash)

# Print each item from the iterator
print(next(superhero))
print(next(superhero))
print(next(superhero))
print(next(superhero))

目前看来就是for循环的替代品,我猜应该是比for循环提高了效率
python中内置的枚举函数

  • 用于将一个可遍历的数据对象(如:列表、元组、字符串等)组合为一个索引序列,同时列出:数据和数据下标
  • 一般在for循坏中使用,可同时得到数据对象的值及对应的索引值
# Unpack and print the tuple pairs
for index1, value1 in enumerate(mutants):
    print(index1, value1)

# Change the start index
for index2, value2 in enumerate(mutants, start=1):
    print(index2, value2)

zip()

使用zip()函数来可以把列表合并,并创建一个元组对的列表

如果各个可迭代对象的元素个数不一致,则返回的对象长度与最短的可迭代对象相同。

利用 * 号操作符,与zip相反,进行解压。

# Create a zip object from mutants and powers: z1
z1 = zip(mutants, powers)

# Print the tuples in z1 by unpacking with *
print(*z1)

# Re-create a zip object from mutants and powers: z1
z1 = zip(mutants, powers)

# 'Unzip' the tuples in z1 by unpacking with * and zip(): result1, result2
result1, result2 = zip(*z1)

# Check if unpacked tuples are equivalent to original tuples
print(result1 == mutants)
print(result2 == powers)
原文地址:https://www.cnblogs.com/gaowenxingxing/p/12236025.html