一级函数

String Manipulation

  • hello : str (
hello = "hello world"[0:5]
foo = "some string"
password = "password"

print(foo[5:11])
'''
string
'''

Omitting Starting Or Ending Indices

  • 索引的时候可以忽略开始index以及结束index:
hello = "hello world"[:5]
foo = "some string"
print(foo[5:])
'''
string
'''

Slicing With A Step

  • 通过步长进行索引
hlo = "hello world"[:5:2]
print(hlo)
'''
hlo
'''

Negative Indexing

  • 负数索引,表示从后向前索引[4::-1]表示从第4个位置开始向前索引。
olleh = "hello world"[4::-1]
print(olleh)
'''
olleh
'''

The Password Data

  • 查找某个模式在密码集中的频数。
'''
passwords : list (<class 'list'>)
['07606374520',
 'piontekendre',
 'rambo144',
 'primoz123',
 'sal1387',
 'EVASLRDG',
 ...
'''
def easy_patterns(pattern):
    count = 0
    for password in passwords:
        if pattern in password:
            count += 1
    return count
countup_passwords = easy_patterns("1234")
print(countup_passwords)
'''
22
'''

First-Class Functions

  • 一级函数

函数式语言中的函数称为一级函数,这意味着函数可在任何其他语言结构(比如变量)可能出现的地方出现。一级函数的存在使得可以以意想不到的方式来使用一级函数,并不得不以不同的方式来思考解决方案,比如在标准数据结构上应用相对一般的操作(加上细节)。这反过来揭示了函数式语言的根本性转变:关注结果,而不是步骤。
一级函数可以作为参数传入到其他函数中。

  • Python中有一个内建函数map(func, ls)可以迭代访问ls列表中的每一个元素然后将其传到func函数中。下面这段代码将列表中的元素转化为整型数据,int在这里是一个转换函数。map返回的是这样的一个对象,因此要将其转换为list打印出来。
ints = list(map(int, [1.5, 2.4, 199.7, 56.0]))
print(ints)
'''
[1, 2, 199, 56]
'''

Average Password Length

password_lengths = list(map(len, passwords))
avg_password_length = sum(password_lengths) / len(passwords)
'''
avg_password_length : 8.429333333333334
'''

More Uses For First-Class Functions

  • 判定是否是回文:my_string == my_string[::-1]倒着索引和正着索引的结果相同就是回文。
def is_palindrome(my_string):
    return my_string == my_string[::-1]

palindrome_passwords = list(filter(is_palindrome, passwords))

Lambda Functions

  • 过滤出偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x : x % 2 == 0, numbers))
print(evens)
'''
[2, 4, 6, 8, 10]
'''

Password Strengths

  • 判断用户密码是否安全(越复杂越安全)
weak_passwords = list(filter(lambda password : len(password) < 6, passwords))
medium_passwords = list(filter(lambda password : len(password) >= 6 and len(password) <= 10, passwords))
strong_passwords = list(filter(lambda password : len(password) > 10, passwords))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值