学习常用的Python内置函数

255 阅读10分钟

Python 以其包含电池的理念而闻名。通过使用丰富的库和模块,你可以获得各种非常强大的工具。Python 也有许多内置的函数,在使用它们之前不需要导入它们。包括的函数远远超过 50 个,但我们将在本教程中看一看一些更常用的内置函数。我们将看看Python函数,如len()、range()、list()、min()、max()、round()、abs()、pow()、sorted()、split()、type()isinstance()。无论你想建立什么类型的应用程序,这些函数都会对你有用。


len()

len和字符串

我们要看的第一个函数是 len() 函数。它接受一个输入,并输出一个代表所提供的输入长度的整数。这通常是一个列表,但也可以是一个字符串或字典。我们可以从一个持有字符串 "Bacon "的肉类变量开始。我们可以使用len()函数来计算一个字符串中有多少个字符。

meat = 'Bacon'
print('Bacon has ' + str(len(meat)) + ' characters')
Bacon has 5 characters

让我们在蔬菜上再试一下这个练习。现在我们有一个名为veggie的变量,我们在其中存储了'西兰花'字符串。通过再次使用len()函数,我们能够计算出 "西兰花 "这个字符串中有多少个字符。

veggie = 'Broccoli'
print('Broccoli has ' + str(len(veggie)) + ' characters')
Broccoli has 8 characters

len和列表

在列表中使用len函数是非常常见的。为了证明这一点,我们将创建一个ticker变量,并在其中存储一个股票代码列表。通过应用len()函数,我们再次看到列表中有4个股票。

tickers = ['lk', 'msft', 'bynd', 'crc']
print('There are ' + str(len(tickers)) + ' tickers in the list')
There are 4 tickers in the list

len函数也常用于循环操作。这是因为你可以用len来设置循环的上限范围。换句话说,只要当前的迭代小于列表的长度,你就可以继续循环。下面是一个例子,我们通过列表的长度进行循环,并打印出每个股票。

for i in range(0, len(tickers)):
    print(tickers[i])
lk
msft
bynd
crc

一个整数的列表也很容易计算出长度。

listofints = [1, 2, 3, 4, 5, 6, 7]
print(len(listofints))
7

现在我们来看一下字典和len函数。正如我们已经学过的,字典有键值对。当对字典使用 len() 时,它计算字典中包含的 key-value 对的数量。它不计算每个键,和每个值的唯一性。这里我们创建了一个包含股票代码和它们的相关价格的字典。我们使用 len 函数来查看长度。

tickerprices = {'lk': 45.50, 'msft': 165.70, 'crc': 8.25}
print('There are ' + str(len(tickerprices)) + ' tickers in the dictionary')
There are 3 tickers in the dictionary

最后,由于 list 可以存储所有不同类型的混合体,我们可以把我们一直在研究的这些不同的 list 放在一个 list 里面,并再次使用 len 函数。

mixedtypes = [tickers, listofints, tickerprices, 'Superbowl', True]
print('There are ' + str(len(mixedtypes)) + ' items in the mixed list')
There are 5 items in the mixed list

range() 和 list()

range() 函数是 Python 中最常用的函数之一。它的用途非常广泛,可以在许多方面使用。使用 range() 函数的第一种方法是简单地将一个整数作为输入传给它。所以我们将创建一个名为 team_members 的变量,并使用 range 来填充这个变量。

team_members = range(25)
print(team_members)
print(len(team_members))
range(0, 25)
25

上面的输出很有意思。如果我们直接打印出这个变量,它显示的是range(0, 25),但是当对这个变量使用len函数时,我们看到事实上有25个成员。值得注意的是,range函数的计数范围是从0到1,比上限范围小。所以如果我们要输出team_members的内容,我们会看到0-24,而不是1-25。

考虑到这一点,我们现在可以看一下list()函数。它接受一个元组作为输入,并输出一个与该元组相同数据的列表。所以我们通过使用 list() 函数从一个不可变的数据集合变成了一个可变的数据集合。我们可以使用list()来列出我们范围实例中的成员。让我们来看看。

print(list(team_members))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

我们可以像这样在for循环的背景下使用list()。

for player in list(team_members):
    print('Player ' + str(player))
Player 0
Player 1
Player 2
Player 3
Player 4
Player 5
Player 6
Player 7
Player 8
Player 9
Player 10
Player 11
Player 12
Player 13
Player 14
Player 15
Player 16
Player 17
Player 18
Player 19
Player 20
Player 21
Player 22
Player 23
Player 24

现在我们可以看到list()函数是如何对我们有用的。下面我们把我们的球员范围分成A队或B队。我们可以通过在每次迭代中跳出球员,并根据他们的号码是偶数还是奇数把他们放在A队或B队中来做到这一点。如果我们不使用list()函数,我们会得到 "AttributeError: 'range' object has no attribute 'pop'"这样的错误。

team_a = []
team_b = []
for player in team_members:
    if player % 2 == 0:
        team_a.append(list(team_members).pop(player))
    else:
        team_b.append(list(team_members).pop(player))

for player in team_a:
    print('Player ' + str(player) + ' is on team A')

for player in team_b:
    print('Player ' + str(player) + ' is on team B')
Player 0 is on team A
Player 2 is on team A
Player 4 is on team A
Player 6 is on team A
Player 8 is on team A
Player 10 is on team A
Player 12 is on team A
Player 14 is on team A
Player 16 is on team A
Player 18 is on team A
Player 20 is on team A
Player 22 is on team A
Player 24 is on team A
Player 1 is on team B
Player 3 is on team B
Player 5 is on team B
Player 7 is on team B
Player 9 is on team B
Player 11 is on team B
Player 13 is on team B
Player 15 is on team B
Player 17 is on team B
Player 19 is on team B
Player 21 is on team B
Player 23 is on team B

min() 和 max()

现在让我们看看 Python 中的 min 和 max 函数。它们所做的正是你所想的,也就是找到一个集合中的最低值或最高值。对于第一个测试,我们只用一个数字范围来演示min和max。我们可以看到,在使用min或max时,会考虑到负整数。

print(max(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5))
print(min(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5))
5
-5

现在我们要去购物了。我们正在看一些牛仔裤,一件毛衣,和一双鞋。其价格分别为40、50和100。

jeans = 40
sweater = 50
shoes = 100

现在我们想看看什么是最高和最低的成本。

print(min(jeans, sweater, shoes))
print(max(jeans, sweater, shoes))
40
100

这些函数对字符串也有作用。也许在购物过程中,我们参观了Kohls, Target, Bed Bath and Beyond, Best Buy和Applebees。下面的例子显示,min和max是根据字母表计算的,而不是根据字符串的长度。

print(min('Kohls', 'Target'))
print(min('Bed Bath Beyond', 'Best Buy', 'Applebees'))
Kohls
Applebees

现在我们还看一件15美元的T恤衫,我们再次使用min和max函数来查看最低和最高价格。

tshirt = 15
print(min(tshirt, sweater, jeans, shoes))
print(max(tshirt, sweater, jeans, shoes))
15
100

round() abs() 和 pow()

Python 内置有 round()、abs() 和 pow() 函数。你可以用这些函数将一个数字四舍五入,得到一个数字的绝对值,或者很容易地将一个数字设置为一个指数。我们可以从一杯弗拉普奇诺开始。考虑到你刚刚花了4.72美元买了一杯这样的东西。我们可以使用round函数来查看这个费用的整数。

frappuccino = 4.72
print(round(frappuccino))
5

round()需要一个可选的第二个参数,指定四舍五入的小数位数。

blueberrypie = 3.14159265359
print(round(blueberrypie, 4))
3.1416

abs()函数使我们能够找到一个数字的绝对值。很多时候,你会想要一个负数的绝对值。这里有几个abs()的例子。

intnum = -7
print('Absolute value of -7 is:', abs(intnum))

floatnum = -2.75
print('Absolute value of -2.75 is:', abs(floatnum))

plantroot = -2.5
print(abs(plantroot))
Absolute value of -7 is: 7
Absolute value of -2.75 is: 2.75
2.5

Python 也有 pow() 函数,用于将一个数提高到一个幂。

print(pow(2,10))
1024

sorted()

我们可以用 Python 中的 sorted() 函数对数据进行排序。sorted 函数需要一个迭代器,这只是我们可以迭代的东西。这意味着像列表、图元、字符串、字典等东西。排序函数然后输出一个列表,将输入的项目进行排序。让我们从一些数字的简单排序开始。

randomnums = [12, -54, 32, 15, -7, 44]
sortednums = sorted(randomnums)
print(sortednums)
[-54, -7, 12, 15, 32, 44]

我们可以通过一个可选的第二个参数来扭转排序顺序。

reversednums = sorted(randomnums, reverse=True)
print(reversednums)
[44, 32, 15, 12, -7, -54]

如果我们有一个字符串的列表,排序函数将按字母顺序排序。

stores = ['Kohls', 'Target', 'Best Buy', 'Walmart', 'Costco']
print(sorted(stores))
print(sorted(stores, reverse=True))
['Best Buy', 'Costco', 'Kohls', 'Target', 'Walmart']
['Walmart', 'Target', 'Kohls', 'Costco', 'Best Buy']

对Dict中的键值对进行排序

通过使用可选的参数,你可以对字典进行一些非常有趣的排序技术。这里我们有一个键值对的字典。

stock_prices = {'Apple': 318.38, 'Google': 1487.64, 'Microsoft': 165.27, 'Cisco': 49.06}

首先,我们想按键来排序,像这样。

for key in sorted(stock_prices.keys()):
    print(key, stock_prices[key])
Apple 318.38
Cisco 49.06
Google 1487.64
Microsoft 165.27

现在我们想按值对字典进行排序。

for key, value in sorted(stock_prices.items(), key=lambda item: item[1]):
    print(key, value)
Cisco 49.06
Microsoft 165.27
Apple 318.38
Google 1487.64

我们也可以为这些添加反向参数。

for key in sorted(stock_prices.keys(), reverse=True):
    print(key, stock_prices[key])
Microsoft 165.27
Google 1487.64
Cisco 49.06
Apple 318.38
for key, value in sorted(stock_prices.items(), key=lambda item: item[1], reverse=True):
    print(key, value)
Google 1487.64
Apple 318.38
Microsoft 165.27
Cisco 49.06

对图元进行排序

有可能在一个列表中存储多个图元。考虑到我们有一个 **shirts**变量,它里面有 4 件衬衫。每个都由一个元组表示。每个元组有3个值,代表衬衫的颜色、尺寸和价格。

shirts = [('Blue', 'XL', 25), ('Red', 'L', 15), ('Green', 'S', 10), ('Yellow', 'M', 20)]

我们可以按元组的第1、2、3个位置排序。

print(sorted(shirts, key=lambda item: item[0]))
[('Blue', 'XL', 25), ('Green', 'S', 10), ('Red', 'L', 15), ('Yellow', 'M', 20)]
print(sorted(shirts, key=lambda item: item[1]))
[('Red', 'L', 15), ('Yellow', 'M', 20), ('Green', 'S', 10), ('Blue', 'XL', 25)]
print(sorted(shirts, key=lambda item: item[2]))
[('Green', 'S', 10), ('Red', 'L', 15), ('Yellow', 'M', 20), ('Blue', 'XL', 25)]

type() 和 isinstance()

在编程时,了解你正在处理的问题是有帮助的。这就是类型函数发挥作用的地方。type()函数接受一个输入,输出是给定输入的类型。这可能是一个字符串,int,或任何有效的对象。这里有几个例子说明这在代码中是如何工作的。

r = range(0, 20)
print(type(r))
<class 'range'>
print(type(7))
<class 'int'>
print(type('Z'))
<class 'str'>
print(type('A simple string'))
<class 'str'>

所以通过上面的例子,你对type()的工作原理有了一个概念。现在我们想看看isinstance()函数是如何工作的。我们需要提供几个简单的类来看看这个动作。

class Car:
    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color


class Truck(Car):
    def fourwheeldrive(self):
        print('four wheel drive engaged')
car = Car('Honda', 'Civic', 'Blue')
print(type(car))
<class '__main__.Car'>
tesla = Car('Tesla', 'Model 3', 'White')
print(type(tesla))
<class '__main__.Car'>
truck = Truck('Toyota', 'Tacoma', 'Red')
print(type(truck))
<class '__main__.Truck'>
print(type(car) == type(truck))
print(type(car) == type(tesla))
False
True
print(isinstance(car, Car))
print(isinstance(truck, Car))
True
True

常用的 Python 内置函数总结

在本教程中,我们对许多 Python 内置函数进行了大量的介绍。在你自己的代码中测试一下它们,看看它们能为你做什么。你会发现,你能够用这些内置函数完成许多你想完成的更常见的任务。