PythonForBeginners-中文系列教程-三-
PythonForBeginners 中文系列教程(三)
Python 中列表中最小元素的索引
原文:https://www.pythonforbeginners.com/basics/index-of-minimum-element-in-a-list-in-python
当我们需要随机访问时,我们在 python 程序中使用列表来存储不同类型的对象。在本文中,我们将讨论在 python 中查找列表中最小元素的索引的不同方法。
使用 for 循环的列表中最小元素的索引
我们在 python 中使用 for 循环来迭代类似 list 的容器对象的元素。为了使用 python 中的 for 循环找到列表中最小元素的索引,我们可以使用 len()
函数和range()
函数。
Python 中的 len()函数
python 中的len()
函数用于查找列表或元组等集合对象的长度。它将类似 list 的容器对象作为其输入参数,并在执行后返回集合对象的长度。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 21, 12]
print("The list is:", myList)
list_len = len(myList)
print("Length of the list is:", list_len)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 21, 12]
Length of the list is: 11
这里,我们将一个包含 11 个元素的列表传递给了len()
函数。执行后,它返回相同的值。
Python 中的 range()函数
range()
函数用于在 python 中生成一系列数字。在最简单的情况下,range()
函数将一个正数 N 作为输入参数,并返回一个包含从 0 到 N-1 的数字序列。您可以在下面的示例中观察到这一点。
sequence = range(11)
print("The sequence is:", sequence)
输出:
The sequence is: range(0, 11)
为了使用 for 循环、 len()
函数和range()
函数在 python 中找到列表中最小元素的索引,我们将使用以下步骤。
- 首先,我们将使用
len()
函数计算输入列表的长度。我们将把该值存储在变量list_len
中。 - 计算完列表的长度后,我们将使用
range()
函数创建一个从 0 到list_len-1
的数字序列。 - 现在,我们将定义一个变量
min_index
并给它赋值 0,假设列表的最小元素出现在索引 0 处。 - 创建序列后,我们将使用 for 循环遍历序列中的数字。迭代时,我们将访问输入列表中每个索引处的元素。
- 在每个索引处,我们将检查当前索引处的元素是否小于列表中
min_index
索引处的元素。如果当前元素小于min_index
处的元素,我们将把min_index
更新为当前索引。
在执行 for 循环后,您将在min_index
变量中获得列表中最小元素的索引。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_index = 0
list_len = len(myList)
for index in range(list_len):
if myList[index] < myList[min_index]:
min_index = index
print("Index of the minimum element is:", min_index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Index of the minimum element is: 3
在上面的方法中,如果列表中多次出现最小元素,您将获得该元素最左边的索引。要获得最小元素所在的最右边的索引,可以在比较列表元素时使用小于或等于运算符,而不是小于运算符。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_index = 0
list_len = len(myList)
for index in range(list_len):
if myList[index] <= myList[min_index]:
min_index = index
print("Index of the minimum element is:", min_index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Index of the minimum element is: 11
使用 min()函数和 Index()方法对列表中的最小元素进行索引
在 python 中,我们可以使用min()
函数和 index()
方法来查找列表中最小元素的索引,而不是使用 for 循环来迭代整个列表。
Python 中的 min()函数
min()
函数用于查找容器对象中的最小元素,如列表、元组或集合。min()
函数将一个类似 list 的集合对象作为它的输入参数。执行后,它返回列表中的最小元素。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_val = min(myList)
print("The minimum value is:", min_val)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
The minimum value is: 1
Python 中的 index()方法
方法的作用是找到一个元素在列表中的位置。当在列表上调用时,index()
方法将一个元素作为它的输入参数。执行后,它返回该元素第一次出现的索引。例如,我们可以在列表中找到元素 23 的索引,如下所示。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
index = myList.index(23)
print("Index of 23 is:", index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Index of 23 is: 2
如上所述,如果单个元素出现多次,index()
方法只返回该元素最左边的索引。如果我们将元素 1 作为输入参数传递给index()
方法,那么输出将是 3,尽管元素 1 也出现在索引 11 处。
如果输入参数中给出的元素不在列表中,那么index()
方法会抛出一个ValueError
异常,表示该元素不在列表中。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
index = myList.index(105)
print("Index of 105 is:", index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
index = myList.index(105)
ValueError: 105 is not in list
这里,我们将 105 作为输入参数传递给了index()
方法。但是,105 不在列表中。因此,程序运行到ValueError
异常,显示 105 不在列表中。
为了使用min()
函数和index()
函数找到列表中最小元素的索引,我们将使用以下步骤。
首先,我们将使用min()
函数找到列表中的最小元素。我们将把该值存储在变量min_val
中。
找到列表中的最小值后,我们将调用列表中的index()
方法,并将min_val
作为其输入参数。执行后,index()
方法将返回列表中最小元素的索引。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_val = min(myList)
index = myList.index(min_val)
print("Index of minimum value is:", index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Index of minimum value is: 3
在元素多次出现的情况下,这种方法只能找到列表中最小元素的最左边的索引。如果想获得最小元素的最右边的索引,可以使用前面讨论的 for 循环和len()
函数。
使用 Numpy 模块的列表中最小元素的索引
模块被设计成以一种有效的方式处理数字和数组。我们还可以使用numpy
模块在 python 中找到列表中最小元素的索引。
numpy
模块为我们提供了argmin()
方法来查找 NumPy 数组中最小元素的索引。当在一个numpy
数组上调用argmin()
方法时,它返回数组中最小元素的索引。
为了使用argmin()
方法获得列表中最小元素的索引,我们将首先把列表转换成一个 numpy 数组。为此,我们将使用array()
函数。
array()
函数将一个列表作为它的输入参数,并返回一个 numpy 数组。您可以在下面的示例中观察到这一点。
import numpy
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
array = numpy.array(myList)
print("The array is:", array)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
The array is: [11 2 23 1 32 12 44 34 55 46 21 1 12]
将列表转换成 numpy 数组后,我们将调用数组上的 argmin()
方法。执行后,argmin()
方法将返回最小元素的索引。
import numpy
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
array = numpy.array(myList)
min_index = array.argmin()
print("Index of minimum element is:", min_index)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Index of minimum element is: 3
当最小元素出现多次时,argmin()
函数将返回最小元素最左边的索引。在上面的例子中,您可以看到argmin()
方法返回 3,即使最小元素 1 也出现在索引 11 处。
多次出现时列表中最小元素的索引
有时,我们可能需要找到列表中最小元素的所有出现。在接下来的部分中,我们将讨论在多次出现的情况下找到列表中最小元素的索引的不同方法。
使用 min()函数和 For 循环的列表中最小元素的索引
当列表中多次出现最小元素时,我们可以使用min()
函数和 for 循环来获取最小元素的索引。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
min_indices
的空列表来存储最小元素的索引。 - 然后,我们将使用
len()
函数找到输入列表的长度。我们将把长度存储在变量list_len
中。 - 在获得列表的长度后,我们将使用
range()
函数创建一个从 0 到 list_len-1 的数字序列。 - 接下来,我们将使用
min()
函数找到列表中的最小元素。 - 找到最小元素后,我们将使用 for 循环遍历数字序列。迭代时,我们将检查列表中当前索引处的元素是否等于最小元素。
- 如果我们找到一个等于最小元素的元素,我们将使用
append()
方法将其索引添加到min_indices
列表中。当在min_indices
列表上调用append()
方法时,该方法将把index
作为其输入参数。执行后,它会将index
作为一个元素添加到min_indices
列表中。 - 如果当前索引处的数字不等于最小元素,我们将移动到下一个元素。
- 如果我们找到一个等于最小元素的元素,我们将使用
在执行 for 循环之后,我们将获得列表中最小元素的索引。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_val = min(myList)
list_indices = []
list_len = len(myList)
sequence = range(list_len)
for index in sequence:
if myList[index] == min_val:
list_indices.append(index)
print("Indices of minimum element are:", list_indices)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Indices of minimum element are: [3, 11]
使用 min()函数和列表理解的列表中最小元素的索引
列表理解用于通过对元素施加一些条件,使用现有列表的元素创建新列表。列表理解的一般语法如下。
new_list=[f(element) for element in existing_list if condition]
这里,
new_list
是执行语句后创建的列表。existing_list
是输入列表。element
表示现有列表中的一个元素。这个变量用于迭代existing_list
。condition
是对元素或f(element)
施加的条件。
为了使用 python 中的列表理解找到列表中最小元素的索引,我们将使用以下步骤。
- 首先,我们将使用
len()
函数找到输入列表的长度。我们将把长度存储在变量list_len
中。 - 在获得列表的长度后,我们将使用
range()
函数创建一个从 0 到 list_len-1 的数字序列。 - 接下来,我们将使用
min()
函数找到列表中的最小元素。 - 在找到最小元素后,我们将使用列表理解来获得最小元素的索引列表。
- 在列表理解中,
- 我们将使用数字序列来代替
existing_list
。 element
将代表数字序列的元素。f(element)
将等于element
。- 代替
condition
,我们将使用输入列表中 index 元素的值应该等于 minimum 元素的条件。
- 我们将使用数字序列来代替
执行该语句后,我们将得到包含列表中最小元素索引的new_list
,如下所示。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
min_val = min(myList)
list_len = len(myList)
sequence = range(list_len)
new_list = [index for index in sequence if myList[index] == min_val]
print("Indices of minimum element are:", new_list)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Indices of minimum element are: [3, 11]
使用 min()函数和 enumerate()函数的列表中最小元素的索引
不使用 len()
函数和range()
函数,我们可以使用enumerate()
函数和min()
函数来查找列表中最小元素的索引。
Python 中的 enumerate()函数
enumerate()
函数用于枚举容器对象的元素,如列表或元组。
enumerate()
函数将一个类似 list 的容器对象作为它的输入参数。执行后,它返回一个包含元组的枚举列表。列表中的每个元组包含两个元素。元组的第一个元素是分配给元素的索引。第二个元素是原始列表中的相应元素,作为输入给enumerate()
函数。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
print("Enumerated list is:", enumerated_list)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Enumerated list is: [(0, 11), (1, 2), (2, 23), (3, 1), (4, 32), (5, 12), (6, 44), (7, 34), (8, 55), (9, 46), (10, 21), (11, 1), (12, 12)]
为了使用enumerate()
函数找到列表中最小元素的索引,我们将使用以下步骤。
- 首先,我们将创建一个名为
min_indices
的空列表来存储最小元素的索引。 - 之后,我们将使用
min()
函数找到输入列表中的最小元素。 - 然后,我们将使用
enumerate()
函数从输入列表中创建枚举列表。 - 获得枚举列表后,我们将使用 for 循环遍历枚举列表中的元组。
- 在迭代元组时,我们将检查当前元组中的元素是否等于最小元素。
- 如果当前元组中的元素等于最小元素,我们将使用
append()
方法将当前索引附加到min_indices
。否则,我们将移动到枚举列表中的下一个元组。
在执行 for 循环之后,我们将获得min_indices
列表中最小元素的索引。您可以在下面的示例中观察到这一点。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
min_indices = []
min_element = min(myList)
for element_tuple in enumerated_list:
index = element_tuple[0]
element = element_tuple[1]
if element == min_element:
min_indices.append(index)
print("Indices of minimum element are:", min_indices)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Indices of minimum element are: [3, 11]
我们可以使用列表理解来查找列表中最小元素的索引,而不是使用 for 循环来迭代枚举列表中的元组,如下所示。
myList = [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
min_element = min(myList)
min_indices = [index for (index, element) in enumerated_list if element == min_element]
print("Indices of minimum element are:", min_indices)
输出:
The list is: [11, 2, 23, 1, 32, 12, 44, 34, 55, 46, 21, 1, 12]
Indices of minimum element are: [3, 11]
结论
在本文中,我们讨论了在 python 中查找列表中最小元素的索引的不同方法。我们还讨论了在最小元素多次出现的情况下,查找列表中最小元素的所有索引。
要在 python 中找到列表中最小元素的索引,我建议您使用带有 index()
方法的min()
函数。在多次出现的情况下,这种方法给出最小元素的最左边的索引。
如果需要在 python 中找到列表中最小元素的最右边的索引,可以使用 for 循环和小于或等于运算符。
在多次出现的情况下,如果需要获得 python 中一个列表中最小元素的所有索引,可以使用带有 for 循环的方法或者带有enumerate()
函数的方法。两者的执行效率几乎相同。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
Python 中的 IndexError
原文:https://www.pythonforbeginners.com/basics/indexerror-in-python
列表是 Python 中最常用的数据结构之一。当您的程序在使用列表时遇到错误时,您可能会收到消息“IndexError:list index out of range”。在本文中,我们将通过研究 Python 中的 IndexError 来讨论如何避免这种错误。
Python 中什么是 IndexError?
IndexError 是 python 中的一个异常,当我们试图访问列表中的元素或列表中不存在的索引中的元组时,就会发生这个异常。例如,我们有一个包含 10 个元素的列表,索引从 0 到 9。如果我们试图访问索引 10 或 11 或更多的元素,它将导致程序引发 IndexError,并显示消息"IndexError:list index out of range",如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The list is:", myList)
index = 10
element = myList[index]
print("Element at index {} is {}".format(index,element))
输出:
The list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
element = myList[index]
IndexError: list index out of range
类似地,如果我们有一个由 10 个元素组成的元组,元素的索引在 0 到 9 的范围内。如果我们试图访问索引为 10 或更多的元素,程序将导致如下的 IndexError。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
element = myTuple[index]
print("Element at index {} is {}".format(index,element))
输出:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
element = myTuple[index]
IndexError: tuple index out of range
这里,我们试图从只有 10 个元素的元组中访问索引为 10 的元素。因此,程序会遇到一个 IndexError 异常。
Python 中如何避免 IndexError?
我们既可以处理索引错误异常,也可以抢占它。为了抢占,我们可以使用 if-else 块。为了在异常发生后对其进行处理,我们可以使用 Python 中的异常处理。
使用 If-Else 块抢占 IndexError
在 python 中避免 IndexError 的唯一方法是确保我们不会从超出范围的索引中访问元素。例如,如果一个列表或元组有 10 个元素,这些元素将只出现在索引 0 到 9 处。因此,我们不应该访问索引为 10 或更大的元素。为此,我们可以使用 if-else 语句来检查索引是否在正确的范围内,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
if index <= 9:
element = myTuple[index]
print("Element at index {} is {}".format(index, element))
else:
print("Index should be smaller.")
输出:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.
使用 Try-Except 块处理 IndexError
或者,我们可以使用 python try except 块来处理程序引发的 IndexError 异常。使用这种方法,我们无法避免 IndexError 异常,但我们可以确保程序不会在引发 IndexError 后过早终止。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("The Tuple is:", myTuple)
index = 10
print("Index is:",index)
try:
element = myTuple[index]
print("Element at index {} is {}".format(index, element))
except IndexError:
print("Index should be smaller.")
输出:
The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Index is: 10
Index should be smaller.
结论
在本文中,我们讨论了 python 中的 IndexError。我们还讨论了超越这个异常的方法。你可以在这篇关于列表理解的文章中阅读更多关于 python 列表的内容。
要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。您可能也会喜欢这篇关于 python simplehttpserver 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中的内部连接数据帧
原文:https://www.pythonforbeginners.com/basics/inner-join-dataframes-in-python
内部联接操作在数据库管理中用于联接两个或多个表。我们还可以对两个 pandas 数据帧执行内部连接操作,因为它们包含表格值。在本文中,我们将讨论如何在 python 中对两个数据帧执行内部连接操作。
什么是内部联接操作?
内部连接操作用于查找两个表之间的交集。例如,假设我们有一个包含学生个人详细信息的表和另一个包含学生成绩的表。如果两个表都有一个公共列,比如说‘Name’
,那么我们可以创建另一个表,其中包含学生的详细信息以及他们在每一行的分数。
为了在 python 中执行内部连接操作,我们可以使用 pandas 数据帧以及join()
方法或merge()
方法。让我们逐一讨论。
程序中使用的文件可以通过下面的链接下载。
使用 merge()方法内部连接两个数据帧
我们可以使用merge()
方法在 python 中对两个数据帧进行内连接操作。当在一个数据帧上调用时,merge()
方法将另一个数据帧作为它的第一个输入参数。同时,它将值 ‘inner’
作为 ‘how’
参数的输入参数。它还将两个数据帧之间的公共列名作为‘on’
参数的输入变量。执行后,它返回一个数据帧,该数据帧是两个数据帧的交集,并且包含两个数据帧中的列。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
resultdf=names.merge(grades,how="inner",on="Name")
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_x Roll_x Name Class_y Roll_y Grade
0 1 11 Aditya 1 11 A
1 1 12 Chris 1 12 A+
2 2 1 Joel 2 1 B
3 2 22 Tom 2 22 B+
4 3 33 Tina 3 33 A-
5 3 34 Amy 3 34 A
您应该记住,输出数据帧将只包含两个表中的那些行,其中作为输入给 ‘on’
参数的列是相同的。来自两个数据帧的所有其他行将从输出数据帧中省略。
如果有同名的列,python 解释器会给列名添加 _x
和_y
后缀。为了识别数据帧中调用了merge()
方法的列,添加了_x
后缀。对于作为输入参数传递给merge()
方法的 dataframe,使用了_y
后缀。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k-means 聚类的文章。
使用 Join()方法内部连接两个数据帧
不使用merge()
方法,我们可以使用join()
方法在数据帧上执行内部连接操作。
当在一个数据帧上调用时,join()
方法将另一个数据帧作为它的第一个输入参数。同时,它将值‘inner’
作为 ‘how’
参数的输入参数。它还将两个数据帧之间的公共列名作为‘on’
参数的输入参数。执行后, join()
方法返回如下所示的输出数据帧。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
grades=grades.set_index("Name")
resultdf=names.join(grades,how="inner",on="Name",lsuffix='_names', rsuffix='_grades')
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_names Roll_names Name Class_grades Roll_grades Grade
0 1 11 Aditya 1 11 A
1 1 12 Chris 1 12 A+
3 2 1 Joel 2 1 B
4 2 22 Tom 2 22 B+
6 3 33 Tina 3 33 A-
7 3 34 Amy 3 34 A
在使用join()
方法时,您还需要记住,要执行连接操作的列应该是作为输入参数传递给join()
方法的 dataframe 的索引。如果数据帧的某些列有相同的列名,您需要使用lsuffix
和rsuffix
参数指定列名的后缀。如果列名相同,传递给这些参数的值可以帮助我们识别哪个列来自哪个数据帧。
结论
在本文中,我们讨论了在 python 中对两个数据帧执行内部连接操作的两种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
在 Python 中的排序列表中插入元素
原文:https://www.pythonforbeginners.com/basics/insert-element-in-a-sorted-list-in-python
通常,我们在 python 中把元素添加到列表的末尾。然而,如果给我们一个排序的列表,并要求我们在插入新元素时保持元素的顺序,这可能会成为一个乏味的任务。在本文中,我们将讨论用 python 在排序列表中插入元素的不同方法。
如何在排序列表中插入元素?
如果给我们一个排序列表,并要求我们在插入新元素时保持元素的顺序,我们首先需要找到可以插入新元素的位置。之后,我们可以使用切片或insert()
方法将元素插入到列表中。
使用切片
为了使用切片在排序列表中插入一个新元素,我们将首先找到元素将被插入的位置。为此,我们将找到列表中的元素大于要插入的元素的索引。然后,我们将列表分成两部分,一部分包含小于要插入的元素的所有元素,另一部分包含大于或等于要插入的元素的所有元素。
创建切片后,我们将创建一个列表,其中要插入的元素是它唯一的元素。此后,我们将连接切片。这样,我们可以创建一个包含新元素的排序列表。您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 5, 6, 7, 8, 9, 10]
print("Original list is:", myList)
element = 4
print("The element to be inserted is:", element)
l = len(myList)
index = 0
for i in range(l):
if myList[i] > element:
index = i
break
myList = myList[:index] + [element] + myList[index:]
print("The updated list is:", myList)
输出:
Original list is: [1, 2, 3, 5, 6, 7, 8, 9, 10]
The element to be inserted is: 4
The updated list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用 insert()方法
在找到大于待插入元素的元素索引后,我们可以使用insert()
方法在排序列表中插入元素。当在列表上调用insert()
方法时,该方法将索引作为其第一个输入参数,将要插入的元素作为第二个输入参数。执行后,元素被插入到列表中。
在找到比要插入的元素大的元素后,我们将使用如下所示的insert()
方法在该元素之前插入该元素。
myList = [1, 2, 3, 5, 6, 7, 8, 9, 10]
print("Original list is:", myList)
element = 4
print("The element to be inserted is:", element)
l = len(myList)
index = 0
for i in range(l):
if myList[i] > element:
index = i
break
myList.insert(index, element)
print("The updated list is:", myList)
输出:
Original list is: [1, 2, 3, 5, 6, 7, 8, 9, 10]
The element to be inserted is: 4
The updated list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
建议阅读:机器学习中的回归与实例
使用等分模块在排序列表中插入元素
bisect
模块为我们提供了insort()
函数,通过它我们可以将一个元素插入到一个排序列表中。 insort()
方法将排序后的列表作为第一个输入参数,将要插入的元素作为第二个输入参数。执行后,元素被插入到列表中。您可以在下面的示例中观察到这一点。
import bisect
myList = [1, 2, 3, 5, 6, 7, 8, 9, 10]
print("Original list is:", myList)
element = 4
print("The element to be inserted is:", element)
bisect.insort(myList, element)
print("The updated list is:", myList)
输出:
Original list is: [1, 2, 3, 5, 6, 7, 8, 9, 10]
The element to be inserted is: 4
The updated list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
结论
在本文中,我们讨论了用 python 在排序列表中插入元素的不同方法。要了解更多关于列表的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
用 Python 在数据帧中插入新列
原文:https://www.pythonforbeginners.com/basics/insert-new-column-into-a-dataframe-in-python
在 python 中,数据帧通常用于处理表格数据。在本文中,我们将讨论如何在 python 中向数据帧中插入新列。
在 Python 中通过索引将新列插入数据帧
要在 dataframe 中添加新列,我们可以像在 python 字典中添加键值对一样使用索引。在这种方法中,我们首先将需要插入的列的所有元素放入一个列表中。之后,我们将使用下面的语法把这个列表作为一个新列添加到 dataframe 中。
datframe_name[column_name]= element_lis
t
这里,
datframe_name
是要插入列的数据帧的名称。column_name
表示包含新列名称的字符串。element_list
表示包含将被插入数据帧的元素的列表。
以下是通过索引将新列插入数据帧的 python 源代码。
import pandas as pd
df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df['Height'] = column_data
print("The dataframe after inserting the column:")
print(df)
输出:
The dataframe before inserting the column:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
The dataframe after inserting the column:
Roll Name Language Height
0 1 Aditya Python 180
1 2 Sam Java 164
2 3 Chris C++ 170
使用 assign()方法将新列插入数据帧
不使用索引,我们可以使用assign()
方法向数据帧中添加一个新列。在 dataframe 上调用assign()
方法时,使用以下语法将列名和新列的元素列表作为关键字参数。
datframe_name.assign(column_name= element_list)
这里,
datframe_name
是要插入列的数据帧的名称。column_name
表示新列的名称。element_list
是包含将被插入数据帧的元素的列表。
执行后,assign()
方法将列插入到数据帧中,并返回更新后的数据帧,如下所示。
import pandas as pd
df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df = df.assign(Height=column_data)
print("The dataframe after inserting the column:")
print(df)
输出:
The dataframe before inserting the column:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
The dataframe after inserting the column:
Roll Name Language Height
0 1 Aditya Python 180
1 2 Sam Java 164
2 3 Chris C++ 170
上述方法用于在末尾插入新列。我们还可以在数据帧的任何位置插入新列。为此,我们可以使用 insert()方法。
使用 Insert()方法将新列插入数据帧
使用 insert()
方法,我们可以在数据帧中的任何位置插入一个新列。在 dataframe 上调用insert()
方法时,该方法将新列插入的位置作为其第一个输入参数,新列的名称作为第二个输入参数,包含新列元素的列表作为第三个输入参数。执行后,它在 dataframe 中的指定位置插入列。您可以在下面的示例中观察到这一点。
import pandas as pd
df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df.insert(1, 'Height', column_data)
print("The dataframe after inserting the column:")
print(df)
输出:
The dataframe before inserting the column:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
The dataframe after inserting the column:
Roll Height Name Language
0 1 180 Aditya Python
1 2 164 Sam Java
2 3 170 Chris C++
结论
在本文中,我们讨论了在 python 中向数据帧中插入新列的三种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
Python 中列表的交集
原文:https://www.pythonforbeginners.com/basics/intersection-of-lists-in-python
列表是 python 中最常用的数据结构之一。有时,我们可能需要找到任意两个给定列表之间的公共元素。在本文中,我们将讨论如何在 python 中对两个列表执行交集操作,以找到它们之间的公共元素。
如何在 python 中执行列表的交集?
要在 python 中执行两个列表的交集,我们只需创建一个输出列表,它应该包含两个输入列表中都存在的元素。例如,如果我们有list1=[1,2,3,4,5,6]
和list2=[2,4,6,8,10,12]
,list1
和list2
的交集将是[2,4,6]
。您可以观察到输出列表的每个元素都属于list1
和list2
。换句话说,输出列表只包含那些同时出现在两个输入列表中的元素。
我们可以使用各种方法在 python 中执行列表的交集。让我们逐一讨论。
python 中使用 For 循环的两个列表的交集
为了执行两个列表的交集,我们将首先创建一个名为newList
的空列表来存储输出列表的元素。之后,我们将遍历第一个输入列表,并检查它的元素是否出现在第二个输入列表中。如果一个元素同时出现在两个列表中,我们将把这个元素附加到newList
中。在执行 for 循环之后,我们将在newList
中获得两个输入列表中的所有元素。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
newList = []
for element in list1:
if element in list2:
newList.append(element)
print("Intersection of the lists is:", newList)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Intersection of the lists is: [2, 4, 6]
或者,您可以遍历第二个输入列表,检查它的元素是否出现在第一个输入列表中。然后,您可以根据元素的存在向newList
添加元素,如下所示。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
newList = []
for element in list2:
if element in list1:
newList.append(element)
print("Intersection of the lists is:", newList)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Intersection of the lists is: [2, 4, 6]
我建议您使用 for 循环遍历较小的列表。这将使您的代码更加高效。
python 中使用集合的两个列表的交集
像并集和交集这样的运算最初是为集合定义的。我们也可以用集合来寻找两个列表的交集。要使用集合对列表执行交集操作,可以将输入列表转换为集合。之后,您可以使用intersection()
方法执行设置交集操作。最后,您可以将输出集转换回列表,如下所示。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
set1 = set(list1)
set2 = set(list2)
newList = list(set1.intersection(set2))
print("Intersection of the lists is:", newList)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Intersection of the lists is: [2, 4, 6]
结论
在本文中,我们讨论了如何在 python 中执行列表的交集。想要了解更多关于列表的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于如何用 python 反转列表的文章。
Python 中的 cmath 模块简介
原文:https://www.pythonforbeginners.com/basics/introduction-to-cmath-module-in-python
在进行数据科学、机器学习或科学计算时,我们经常需要对包括复数在内的数字数据类型进行计算。在本文中,我们将使用 python 中的 cmath 模块,使用该模块中提供的不同方法对复数执行操作。
计算复数的相位
复数的相位定义为实轴和代表复数的向量之间的角度。使用 cmath 模块,我们可以使用 phase()方法找到一个复数的相位。phase 方法将一个复数作为输入,并返回一个表示该复数相位的浮点数,如下所示。
import cmath
myNum=3+2j
print("The complex number is:",myNum)
myPhase= cmath.phase(myNum)
print("Phase of the complex number is:",myPhase)
输出:
The complex number is: (3+2j)
Phase of the complex number is: 0.5880026035475675
复数的极坐标
在极坐标中,复数被定义为由作为第一元素的复数的模和作为第二元素的复数的相位组成的元组。我们可以用 python 中的 polar()方法求一个复数的极坐标。polar()方法将一个复数作为输入,并返回一个表示极坐标的元组,如下所示。
import cmath
myNum=3+2j
print("The complex number is:",myNum)
myPol= cmath.polar(myNum)
print("Polar coordinates of the complex number are:",myPol)
输出:
The complex number is: (3+2j)
Polar coordinates of the complex number are: (3.605551275463989, 0.5880026035475675)
如果我们知道一个复数的模数和相位,也就是说,如果我们知道一个复数的极坐标,我们可以使用 rect()方法获得该复数。rect()方法将模数作为第一个参数,将复数的相位作为第二个参数,并返回相应的复数,如下所示。
import cmath
myPol= (3.605551275463989, 0.5880026035475675)
print("Polar coordinates of the complex number are:",myPol)
print("Modulus of the complex number is:",myPol[0])
print("Phase of the complex number is:",myPol[1])
myRec=cmath.rect(myPol[0],myPol[1])
print("Complex number in rectangular form is:",myRec)
输出:
Polar coordinates of the complex number are: (3.605551275463989, 0.5880026035475675)
Modulus of the complex number is: 3.605551275463989
Phase of the complex number is: 0.5880026035475675
Complex number in rectangular form is: (3+1.9999999999999996j)
cmath 模块中的常数
cmath 模块还提供某些数学常数,如无穷大、NaN 和 pi,它们在数学计算中很有用。下面的示例中给出了一些常数。
import cmath
print("Given below are some of the constants defined in cmath module.")
print("e:",cmath.e)
print("Infinity (real axis):",cmath.inf)
print("Infinity (Imaginary axis):",cmath.infj)
print("NaN (real):",cmath.nan)
print("NaN (imaginary):",cmath.nanj)
print("Pi:",cmath.pi)
print("Tau:",cmath.tau)
输出:
Given below are some of the constants defined in cmath module.
e: 2.718281828459045
Infinity (real axis): inf
Infinity (Imaginary axis): infj
NaN (real): nan
NaN (imaginary): nanj
Pi: 3.141592653589793
Tau: 6.283185307179586
cmath 模块中的三角函数
对于复数的数学计算,cmath 模块提供了一组三角函数。所有三角函数都将复数作为输入,并返回一个表示三角函数相应输出的复数。下面讨论一些例子。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Sine of the complex number is:",cmath.sin(myNum))
print("Cosine of the complex number is:",cmath.cos(myNum))
print("Tangent of the complex number is:",cmath.tan(myNum))
print("Inverse Sine of the complex number is:",cmath.asin(myNum))
print("Inverse Cosine of the complex number is:",cmath.acos(myNum))
print("Inverse Tangent of the complex number is:",cmath.atan(myNum))
输出:
Complex number is: (3+2j)
Sine of the complex number is: (0.5309210862485197-3.59056458998578j)
Cosine of the complex number is: (-3.7245455049153224-0.5118225699873846j)
Tangent of the complex number is: (-0.009884375038322495+0.965385879022133j)
Inverse Sine of the complex number is: (0.9646585044076028+1.9686379257930964j)
Inverse Cosine of the complex number is: (0.6061378223872937-1.9686379257930964j)
Inverse Tangent of the complex number is: (1.3389725222944935+0.14694666622552977j)
cmath 模中的双曲函数
就像三角函数一样,cmath 模块也为 python 中的数学计算提供了双曲函数和反双曲三角函数。所有这些函数都将一个复数作为输入,并根据其性质返回一个表示双曲或反双曲三角函数输出的复数。下面是一些例子。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Hyperbolic Sine of the complex number is:",cmath.sinh(myNum))
print("Hyperbolic Cosine of the complex number is:",cmath.cosh(myNum))
print("Hyperbolic Tangent of the complex number is:",cmath.tanh(myNum))
print("Inverse Hyperbolic Sine of the complex number is:",cmath.asinh(myNum))
print("Inverse Hyperbolic Cosine of the complex number is:",cmath.acosh(myNum))
print("Inverse Hyperbolic Tangent of the complex number is:",cmath.atanh(myNum))
输出:
Complex number is: (3+2j)
Hyperbolic Sine of the complex number is: (-4.168906959966565+9.15449914691143j)
Hyperbolic Cosine of the complex number is: (-4.189625690968807+9.109227893755337j)
Hyperbolic Tangent of the complex number is: (1.00323862735361-0.003764025641504249j)
Inverse Hyperbolic Sine of the complex number is: (1.9833870299165355+0.5706527843210994j)
Inverse Hyperbolic Cosine of the complex number is: (1.9686379257930964+0.6061378223872937j)
Inverse Hyperbolic Tangent of the complex number is: (0.22907268296853878+1.4099210495965755j)
cmath 模块中的对数函数
cmath 模块提供了两种方法,即 log()和 log10(),用于复数的对数计算。log()函数将一个复数作为第一个输入,并将一个可选参数作为对数函数的底数。当我们只将复数作为输入传递给 log()函数时,它返回以“e”为基数的复数的自然对数。当我们还将第二个参数(即 base)传递给 log()函数时,它将使用提供的底数计算复数的对数。这可以从下面的例子中看出。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Natural log of the complex number is:",cmath.log(myNum))
print("Logarithm of the complex number with base 5 is:",cmath.log(myNum,5))
输出:
Complex number is: (3+2j)
Natural log of the complex number is: (1.2824746787307684+0.5880026035475675j)
Logarithm of the complex number with base 5 is: (0.7968463205835412+0.36534655919610926j)
log10()方法计算以 10 为底的复数的对数,如下所示。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Logarithm of the complex number with base 10 is:",cmath.log10(myNum))
输出:
Complex number is: (3+2j)
Logarithm of the complex number with base 10 is: (0.5569716761534184+0.255366286065454j)
cmath 模块中的幂函数
cmath 模块为 python 中的计算提供了两个幂函数,即 exp()和 sqrt()。exp()函数接受一个复数作为输入,并返回一个表示输入的指数值的复数。这可以从下面的例子中看出。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Exponential of the complex number is:",cmath.exp(myNum))
输出:
Complex number is: (3+2j)
Exponential of the complex number is: (-8.358532650935372+18.263727040666765j)
sqrt()函数也接受一个复数作为输入,并返回表示输入平方根的复数,如下所示。
import cmath
myNum=3+2j
print("Complex number is:",myNum)
print("Square root of the complex number is:",cmath.sqrt(myNum))
输出:
Complex number is: (3+2j)
Square root of the complex number is: (1.8173540210239707+0.5502505227003375j)
结论
在本文中,我们研究了 cmath 模块中的函数和方法,以便在 Python 中对复数执行数学运算。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
Python 中的 Deque 模块介绍
原文:https://www.pythonforbeginners.com/deque/introduction-to-deque-module-in-python
双端队列是一种线性数据结构,我们可以在它的两端插入或删除元素,即它支持后进先出(LIFO)操作以及先进先出(FIFO)操作。dequee 模块是 python 中集合库的一部分,我们可以使用 dequee 模块中内置的方法来执行插入、删除或计算 dequee 中元素的数量。在本文中,我们将尝试通过用 python 实现程序来理解 deque 模块。
如何使用 Python 中的 deque 模块?
为了在 python 中使用 deque,我们将首先使用 import 语句导入模块,如下所示。
from collections import deque
导入 deque 模块后,我们可以使用 deque()方法声明一个 deque 对象。dequee()方法将 list 或 tuple 之类的可迭代对象作为输入参数,创建一个 dequee 对象并返回对 dequee 对象的引用。这可以如下实现。
from collections import deque
myDeque= deque([1,2,3,4,5])
print("The created deque is:")
print(myDeque)
输出:
The created deque is:
deque([1, 2, 3, 4, 5])
如何在一个队列中插入元素?
我们可以使用 collections.deque 模块中定义的几种方法在 deque 中插入元素。
要在队列的开头插入一个元素,我们可以使用 appendleft()方法。appendleft()方法在 dequee 对象上调用时接受一个元素作为输入,并将该元素添加到 dequee 的开头。这可以从下面的例子中看出。
print("Deque before insertion:")
print(myDeque)
myDeque.appendleft(0)
print("Deque after insertion of element 0 at start:")
print(myDeque)
输出:
Deque before insertion:
deque([1, 2, 3, 4, 5])
Deque after insertion of element 0 at start:
deque([0, 1, 2, 3, 4, 5])
要在队列末尾插入一个元素,我们可以使用 append()方法。append()方法在 dequee 对象上调用时接受一个元素作为输入,并将该元素添加到 dequee 的末尾。这可以从下面的例子中看出。
print("Deque before insertion:")
print(myDeque)
myDeque.append(6)
print("Deque after insertion of element 6 at end:")
print(myDeque)
输出:
Deque before insertion:
deque([0, 1, 2, 3, 4, 5])
Deque after insertion of element 6 at end:
deque([0, 1, 2, 3, 4, 5, 6])
我们也可以在一个队列中同时插入多个条目。要在队列的开始插入多个元素,我们可以使用 extendleft()方法。在 dequee 上调用 extendleft()方法时,该方法将 list 或 tuple 等 iterable 作为输入,并按照与输入中传递的顺序相反的顺序将元素添加到 dequee 的开头,如下所示。
print("Deque before insertion:")
print(myDeque)
myDeque.extendleft([-2,-3,-4])
print("Deque after insertion of multiple elements at start:")
print(myDeque)
输出:
Deque before insertion:
deque([0, 1, -1, 2, 3, 4, 5, 6])
Deque after insertion of multiple elements at start:
deque([-4, -3, -2, 0, 1, -1, 2, 3, 4, 5, 6])
要在队列末尾插入多个元素,我们可以使用 extend()方法。extend()方法在 dequee 上调用时将 list 或 tuple 等可迭代对象作为输入,并将元素添加到 dequee 的末尾,如下所示。
print("Deque before insertion:")
print(myDeque)
myDeque.extend([-5,-6,-7])
print("Deque after insertion of multiple elements at end:")
print(myDeque)
输出:
Deque before insertion:
deque([-4, -3, -2, 0, 1, -1, 2, 3, 4, 5, 6])
Deque after insertion of multiple elements at end:
deque([-4, -3, -2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6, -7])
我们还可以使用 insert()方法在队列中的特定位置插入一个元素。在 deque 上调用 insert()方法时,该方法将必须插入元素的索引作为第一个参数,将元素本身作为第二个参数,并在指定的索引处插入元素,如下所示。
print("Deque before insertion:")
print(myDeque)
myDeque.insert(2,-1)
print("Deque after insertion of element -1 at index 2:")
print(myDeque)
输出:
Deque before insertion:
deque([0, 1, 2, 3, 4, 5, 6])
Deque after insertion of element -1 at index 2:
deque([0, 1, -1, 2, 3, 4, 5, 6])
如何在 Python 中删除 deque 中的元素?
我们可以从队列的开始和结尾删除一个元素。为了从队列的开始处删除一个元素,我们使用 popleft()方法。对 dequee 调用 popleft()方法时,会删除 dequee 中的第一个元素,并返回该元素的值。如果队列为空,popleft()方法将引发一个名为IndexError
的异常,并显示一条消息“从空队列中弹出”。为了处理这个异常,我们可以使用除了之外的 python try 来使用异常处理。这可以如下实现。
print("Deque before deletion of leftmost element:")
print(myDeque)
try:
myDeque.popleft()
except IndexError:
print("Deque is empty")
print("Deque after deletion of leftmost element:")
print(myDeque)
输出:
Deque before deletion of leftmost element:
deque([-3, -2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6, -7])
Deque after deletion of leftmost element:
deque([-2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6, -7])
要从队列末尾删除一个元素,我们可以使用 pop()方法。在 dequee 上调用 pop()方法时,会删除 dequee 中的最后一个元素,并返回该元素的值。如果队列为空,pop()方法将引发一个名为IndexError
的异常,并显示一条消息“从空队列中弹出”。为了处理这个异常,我们可以使用 python try except 进行异常处理。这可以如下实现。
print("Deque before deletion of rightmost element:")
print(myDeque)
try:
myDeque.pop()
except IndexError:
print("Deque is empty")
print("Deque after deletion of rightmost element:")
print(myDeque)
输出:
Deque before deletion of rightmost element:
deque([-2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6, -7])
Deque after deletion of rightmost element:
deque([-2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6])
我们还可以使用 remove()方法从队列中删除任何特定的元素。在 deque 上调用 remove 方法时,该方法将元素作为输入,并删除该元素的第一个匹配项。当要删除的元素不在 dequee 中时,remove 方法会引发 ValueError 异常,并显示消息“dequee . remove(x):x 不在 dequee 中”。为了处理这个异常,我们可以使用 python 中的 try except 块来进行异常处理。这可以如下实现。
print("Deque before deletion of element -1:")
print(myDeque)
try:
myDeque.remove(-1)
except ValueError:
print("Value is not present in deque")
print("Deque after deletion of element -1:")
print(myDeque)
输出:
Deque before deletion of element -1:
deque([-2, 0, 1, -1, 2, 3, 4, 5, 6, -5, -6])
Deque after deletion of element -1:
deque([-2, 0, 1, 2, 3, 4, 5, 6, -5, -6])
统计特定元素在队列中的出现次数
为了计算一个元素在队列中出现的次数,我们可以使用 count()方法。在 dequee 上调用 count()方法时,该方法将元素作为输入,返回元素在 dequee 中出现的次数。这可以从下面的例子中看出。
print("Deque is:")
print(myDeque)
n=myDeque.count(2)
print("Number of occurrences element 2 in deque is:")
print(n)
输出:
Deque is:
deque([-2, 0, 1, 2, 3, 4, 5, 6, -5, -6])
Number of occurrences element 2 in deque is:
1
反转队列中的元素
我们可以使用 reverse()方法反转 deque 中的元素。在 deque 上调用 reverse()方法时,会按如下方式反转元素的顺序。
print("Deque is:")
print(myDeque)
myDeque.reverse()
print("Reversed deque is:")
print(myDeque)
输出:
Deque is:
deque([-2, 0, 1, 2, 3, 4, 5, 6, -5, -6])
Reversed deque is:
deque([-6, -5, 6, 5, 4, 3, 2, 1, 0, -2])
搜索队列中的元素
我们可以使用 index()方法搜索队列中的元素。在 deque 上调用 index()方法时,该方法将元素、开始搜索的 start index 和停止搜索的 end index 分别作为第一、第二和第三个参数,并返回元素所在的第一个索引。当元素不存在时。index()方法引发一个ValueError
,并显示一条消息,指出元素不在队列中。我们可以使用 try except 块来处理异常,并给出如下正确的输出。
print("Deque is:")
print(myDeque)
try:
n=myDeque.index(4,0,9)
print("Element 4 is at index")
print(n)
except ValueError:
print("Value is not present in deque")
输出:
Deque is:
deque([-6, -5, 6, 5, 4, 3, 2, 1, 0, -2])
Element 4 is at index
4
如何在 Python 中旋转一个 deque?
我们可以使用 rotate()方法将队列向右旋转指定的步数。在 dequee 上调用 rotate()方法时,将 dequee 必须旋转的步数作为输入,并按如下方式旋转数组。
print("Deque is:")
print(myDeque)
myDeque.rotate(3)
print("deque after rotationg three steps rightwards is:")
print(myDeque)
输出:
Deque is:
deque([-6, -5, 6, 5, 4, 3, 2, 1, 0, -2])
deque after rotationg three steps rightwards is:
deque([1, 0, -2, -6, -5, 6, 5, 4, 3, 2])
结论
在本文中,我们介绍了 python 中的 deque 模块及其方法。为了更深入地了解它,并理解 dequee 与其他数据结构(如 python dictionary 、list 和 set)的不同之处,请将代码复制到您的 IDE 中,并尝试 dequee 操作。请继续关注更多内容丰富的文章。
IPython 简介
原文:https://www.pythonforbeginners.com/basics/ipython-a-short-introduction
概观
本文的目标是写一篇关于 IPython 的简短介绍。虽然 IPython 有两个主要组件(一个交互式 Python shell 和一个交互式并行计算的架构),但本文将讨论 Python Shell。我将把并行计算部分留待下次。将来我还会写关于“IPython 笔记本”的文章,这是一个基于 web 的交互环境,在这里你可以将代码执行、文本、数学、情节和富媒体结合到一个文档中。众所周知,IPython 可以在以下操作系统上工作:Linux、大多数其他类似 Unix 的操作系统(AIX、Solaris、BSD 等)。)Mac OS X Windows (CygWin,XP,Vista 等。)
IPython 是什么?
IPython 是 Python 编程语言的交互式 shell,它提供了增强的自省、附加的 shell 语法、制表符补全和丰富的历史记录。来源
为什么选择 IPython?
默认的交互式 Python shell 有时感觉很简单。有一种替代方法叫做“IPython ”,你可以通过输入 apt-get install IPython 来安装它(参见下面的安装部分)。当它安装好后,你可以通过在终端中输入 IPython 来启动它。IPython 提供了你在基本解释器中可以得到的所有东西,但还有很多额外的东西(行号、高级编辑、更多功能、帮助功能等)
安装 IPython?
正如我在上面写的,如果你在 Ubuntu 系统上,你可以通过在你的终端中输入 apt-get install IPython 来安装 IPython。如果您在另一个系统上,请查看这里的让我们来看看在运行 Mac 的系统上安装会是什么样子。
# To see if I've ipython installed, I simply type "ipython" in my terminal.
$ ipython
-bash: ipython: command not found
所以我的系统上没有安装 IPython。让我们安装它
$ sudo easy_install ipython
Password:
Searching for ipython
Reading http://pypi.python.org/simple/ipython/
Reading http://ipython.scipy.org
Reading http://ipython.scipy.org/dist
Reading http://ipython.org
Reading https://github.com/ipython/ipython/downloads
Reading http://ipython.scipy.org/dist/0.8.4
Reading http://ipython.scipy.org/dist/0.9.1
Reading http://archive.ipython.org/release/0.12.1
Reading http://ipython.scipy.org/dist/old/0.9
Reading http://ipython.scipy.org/dist/0.10
Reading http://archive.ipython.org/release/0.11/
Reading http://archive.ipython.org/release/0.12
Best match: ipython 0.13.1
Downloading http://pypi.python.org/packages/2.7/i/ipython/ipython-0.13.1-py2.7.egg#md5..
Processing ipython-0.13.1-py2.7.egg
creating /Library/Python/2.7/site-packages/ipython-0.13.1-py2.7.egg
Extracting ipython-0.13.1-py2.7.egg to /Library/Python/2.7/site-packages
Adding ipython 0.13.1 to easy-install.pth file
Installing ipcontroller script to /usr/local/bin
Installing iptest script to /usr/local/bin
Installing ipcluster script to /usr/local/bin
Installing ipython script to /usr/local/bin
Installing pycolor script to /usr/local/bin
Installing iplogger script to /usr/local/bin
Installing irunner script to /usr/local/bin
Installing ipengine script to /usr/local/bin
Installed /Library/Python/2.7/site-packages/ipython-0.13.1-py2.7.egg
Processing dependencies for ipython
Finished processing dependencies for ipython
当我这次在终端中键入 IPython 时,它启动了,但是我得到一条错误消息:
$ ipython
/Library/Python/2.7/site-packages/ipython-0.13.1-py2.7.egg/IPython/utils/rlineimpl.py:111:
RuntimeWarning:
libedit detected - readline will not be well behaved, including but not limited to:
* crashes on tab completion
* incorrect history navigation
* corrupting long-lines
* failure to wrap or indent lines properly
It is highly recommended that you install readline, which is easy_installable:
easy_install readline
Note that `pip install readline` generally DOES NOT WORK, because
it installs to site-packages, which come *after* lib-dynload in sys.path,
where readline is located. It must be `easy_install readline`, or to a custom
location on your PYTHONPATH (even --user comes after lib-dyload).
要解决这个问题,只需输入 easy_install readline(如上所述)
$sudo easy_install readline
Searching for readline
Reading http://pypi.python.org/simple/readline/
Reading http://github.com/ludwigschwardt/python-readline
Reading http://www.python.org/
Best match: readline 6.2.4.1
Downloading http://pypi.python.org/packages/2.7/r/readline/readline-6.2.4.1-py2.7-macosx..
Processing readline-6.2.4.1-py2.7-macosx-10.7-intel.egg
creating /Library/Python/2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg
Extracting readline-6.2.4.1-py2.7-macosx-10.7-intel.egg to /Library/Python/2.7/site-packages
Adding readline 6.2.4.1 to easy-install.pth file
Installed /Library/Python/2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg
Processing dependencies for readline
Finished processing dependencies for readline
安装了 readline,一切都应该没问题了。
$ ipython
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
IPython 现已安装在您的系统上。
启动 IPython
通过在终端中键入“ ipython ”来启动 IPython。
$ ipython
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
从文件运行 Python 代码
IPython 的基本工作流程是使用文本编辑器编辑代码。保存文件并将其加载到 IPython 中。如果您想测试代码的交互性,请使用%run -i,否则,您可以只使用%run。如果出现问题,只需返回文本编辑器,修复错误,保存并退出。然后返回 IPython,再次运行该文件。要运行保存到文件中的 python 代码(例如 hello.py),可以使用命令 %run (在我们的例子中是%run hello.py)。IPython 将在当前文件夹中查找该文件。您可以使用 ls 命令列出当前文件夹中文件的内容,hello.py 中的代码将会运行,但是其中的函数将不可用于交互式调用。如果您想测试代码的交互性,那么在使用%run 时,您必须添加-i 开关。运行它交互的命令是 %run -i hello.py
制表符结束
制表符补全,尤其是对于属性来说,是一种探索您正在处理的任何对象的结构的便捷方式。 source 要使用补全,请键入您希望 shell 匹配的模式,然后按 Tab 键。只需键入 object_name。除了 Python 对象和关键字之外,要查看对象的属性,制表符补全也适用于文件名和目录名。
In [1]: from sys import std
stderr stdin stdout
In [1]: from urllib2 import url
url2pathname urlopen urlparse
宏指令
IPython 宏非常适合反复执行相同的代码。宏允许用户将一个名称与 Python 代码的一部分相关联,这样以后就可以通过引用该名称来运行代码。它们可以通过“%edit”魔法命令进行编辑
使用 Python 调试器(pdb)
Python 调试器(pdb)是一个强大的交互式调试器,它允许你单步调试代码、设置断点、观察变量等。启用自动 pdb 调用后,当 Python 遇到未处理的异常时,Python 调试器将自动启动。调试器中的当前行将是发生异常的代码行。如果您使用–pdb 选项启动 IPython,那么您可以在每次代码触发未捕获的异常时调用 Python pdb 调试器。也可以随时使用%pdb magic 命令切换此功能。来源
轮廓
概要文件是包含配置和运行时文件的目录,比如日志、并行应用程序的连接信息和 IPython 命令历史。概要文件使得为特定项目保存单独的配置文件、日志和历史变得容易。通过下面的命令可以很容易地创建概要文件。$ ipython profile create profile_name这会将名为 profile _ name 的目录添加到您的 IPython 目录中。然后,您可以通过在命令行选项中添加–profile =来加载这个概要文件。所有 IPython 应用程序都支持概要文件。这个命令应该创建并打印配置文件的安装路径。要使用概要文件,只需将概要文件指定为 ipython 的一个参数。$ IPython–profile = profile _ nameIPython 在 IPython/config/profile 中附带了一些样例概要文件。
启动文件
在 profile_/startup 目录中,您可以将任何 python(.py)或 IPython(。ipy)文件,您希望 IPython 一启动就运行这些文件。当前在我的 profile_default/startup 目录中唯一的东西是一个自述文件。该文件的内容应该类似于“这是 IPython 启动目录。py 和。每当您加载此配置文件时,此目录中的 ipy 文件将在通过 exec_lines 或 exec_files 可配置文件指定的任何代码或文件之前运行。文件将按字典顺序运行,因此您可以使用前缀控制文件的执行顺序,例如:00-first . py 50-middle . py 99-last . ipy " OK。太好了,让我们试试这个。在编辑器中创建新文件:
$ vim calc.py
# This is a small python script calculating numbers
a = 1 + 1
b = 2 * 2
c = 10 / 2
d = 10 - 5
print a,b,c,d
退出编辑器并启动 IPython
$ ipython
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
3
>>> 2 4 5 5
In [1]: %run calc.py
2 4 5 5
这样就可以使用启动文件中的所有内容,而无需在每次重新输入 IPython 时重新键入它们。
IPython 中的命令
IPython“magic”命令通常以%开头,但是如果标志%automagic 设置为 on(这是默认设置),那么可以调用前面没有%的 magic 命令。IPython 会检查您输入的命令是否符合它的神奇关键字列表。如果命令是一个神奇的关键字,IPython 知道如何处理它。如果它不是一个神奇的关键字,它会让 Python 知道如何处理它。
lxmagic
列出所有内置命令,称为魔术命令。如果变量具有相同的名称,这些变量会以%作为前缀来区分。
#In [57]: lsmagic
Available line magics:
%alias %alias_magic %autocall %autoindent %automagic %bookmark %cd %colors %config
%cpaste %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history
%install_default_config %install_ext %install_profiles %killbgscripts %load %load_ext
%loadpy %logoff %logon %logstart %logstate %logstop %lsmagic %macro %magic
%notebook %page %paste %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd
%pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab
%quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %run
%save %sc %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls
%whos %xdel %xmode
Available cell magics:
%%! %%bash %%capture %%file %%perl %%prun %%ruby %%script %%sh %%sx %%system
%%timeit
Automagic is ON, % prefix IS NOT needed for line magics.
帮助命令
%quickref 显示了 IPython 中可用的“神奇”命令。如果您在 IPython 中键入%quickref,您将看到快速参考卡,其中包含许多有用的帮助。IPython —增强的交互式 Python —快速参考卡= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " "很有用。如果你输入?在镜头后?,您将看到关于函数 len 的文档。打字?在一个名称之后,将会给出与该名称相关的对象的信息,
>>>len?
Type: builtin_function_or_method
String Form:
Namespace: Python builtin
Docstring:
len(object) -> integer
Return the number of items of a sequence or mapping.
>>>str?
Type: type
String Form:<type 'str'="">
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
更多命令
%reset 重置交互环境 %hist 允许您通过键入[55]:hist-g math 19:import math 55:hist-g math% paste使用剪贴板中的文本,例如,如果您使用 Ctrl+C 复制了代码,则可以查看您的输入历史的任何部分% hist-g somestringSearch(‘grep’)。该命令清除某些字符,并尝试找出代码应该如何格式化。%edit% edit 命令(及其别名% ed)将调用您环境中的编辑器集作为编辑器。 %who 此函数列出对象、函数等。已添加到当前命名空间中的模块,以及已导入的模块。In [50]: who 交互式命名空间为空。
In [51]: import sys
In [52]: import os
In [53]: who
os sys
系统外壳访问
任何以!开头的输入行!字符被逐字传递(减去!)到底层操作系统。比如打字!ls 将在当前目录中运行' ls'。要在系统 shell 中运行任何命令:
In [2]: !ping www.google.com
PING www.google.com (173.194.67.104): 56 data bytes
64 bytes from 173.194.67.104: icmp_seq=0 ttl=49 time=6.096 ms
64 bytes from 173.194.67.104: icmp_seq=1 ttl=49 time=5.963 ms
^C
您可以将输出捕获到一个 Python 列表中,例如:files =!ls。
别名
IPython 附带了一些预定义的别名。您的所有$PATH 都已经作为 IPython 别名加载,因此您应该能够键入任何普通的系统命令并执行它。In [1]: %alias 别名总数:16 Out[1]: ('lk ',' ls -F -l %l | grep ^l'),(' ll ',' ls -F -l '),(' ls ',' ls -F '),…更全面的文档可以在这里找到:http://ipython . org/ipython-doc/stable/interactive/tutorial . htmlhttp://wiki.ipython.org/index.php?title=Cookbook
在 Python 中迭代字典
原文:https://www.pythonforbeginners.com/dictionary/iterating-over-dictionary-in-python
字典是 python 中最常用的数据结构之一。它包含键值对形式的数据。在使用字典处理数据时,我们可能需要迭代字典中的条目来更改值或读取字典中的值。在本文中,我们将看到 python 中遍历字典的各种方法。
使用 for 循环迭代字典
当我们在 python 中使用 for 循环遍历列表或元组时,我们也可以使用 for 循环遍历 python 字典。
当我们试图使用 for 循环迭代一个字典时,它会隐式调用__iter__()
方法。__iter__()
方法返回一个迭代器,在这个迭代器的帮助下,我们可以遍历整个字典。正如我们所知,python 中的字典是使用键索引的,由__iter__()
方法返回的迭代器遍历 python 字典中的键。
因此,使用 for 循环,我们可以迭代并访问字典的所有键,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The keys in the dictionary are:")
for x in myDict:
print(x)
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The keys in the dictionary are:
name
acronym
about
在输出中,我们可以看到所有的键都被打印出来了。在 for 循环中,迭代器x
遍历字典中的所有键,然后打印出来。
使用 for 循环获得字典的键后,我们还可以如下迭代字典中的值。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The values in the dictionary are:")
for x in myDict:
print(myDict[x])
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The values in the dictionary are:
PythonForBeginners
PFB
Python Tutorials Website
在上面的代码中,我们简单地获得了一个迭代器,它遍历中的键,然后我们使用语法dict_name[key_name]
访问与键相关的值,然后输出这些值。
迭代字典的关键字
我们可以使用keys()
方法来迭代字典的键。当在字典上调用时,keys()
方法返回字典中的键列表,然后我们可以遍历列表来访问字典中的键,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The keys in the dictionary are:")
keyList=myDict.keys()
for x in keyList:
print(x)
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The keys in the dictionary are:
name
acronym
about
一旦我们在列表中有了键,我们还可以访问与字典的键相关的值,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The values in the dictionary are:")
keyList=myDict.keys()
for x in keyList:
print(myDict[x])
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The values in the dictionary are:
PythonForBeginners
PFB
Python Tutorials Website
在 python 中迭代字典的值
如果我们只想访问字典中的值,我们可以借助于values()
方法来实现。在字典上调用 values()
方法时,会返回字典中所有值的列表。我们可以使用values()
方法和 for 循环访问字典中的值,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The values in the dictionary are:")
valueList=myDict.values()
for x in valueList:
print(x)
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The values in the dictionary are:
PythonForBeginners
PFB
Python Tutorials Website
在输出中,我们可以看到字典中的所有值都被逐个打印出来。
用 python 迭代字典中的条目
我们可以使用items()
方法迭代并访问键值对。在字典上调用items()
方法时,会返回一个元组列表,这些元组具有成对的键和值。每个元组在其0th
索引上有一个键,并且与该键相关联的值出现在元组的1st
索引上。我们可以使用如下所示的items()
方法来访问键值对。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
print("The items in the dictionary are:")
itemsList=myDict.items()
for x in itemsList:
print(x)
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The items in the dictionary are:
('name', 'PythonForBeginners')
('acronym', 'PFB')
('about', 'Python Tutorials Website')
除了使用items()
方法迭代字典中的条目,我们还可以在 for 循环中使用两个迭代器迭代字典的键和值,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB","about":"Python Tutorials Website"}
print("The dictionary is:")
print(myDict)
itemList=myDict.items()
print("The key value pairs in the dictionary are:")
for x,y in itemList:
print(x,end=":")
print(y)
输出:
The dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB', 'about': 'Python Tutorials Website'}
The key value pairs in the dictionary are:
name:PythonForBeginners
acronym:PFB
about:Python Tutorials Website
在上面的程序中,第一个迭代器迭代字典中的关键字,第二个迭代器迭代与这些关键字相关联的各个值,这些关键字以元组的形式存在,包含由items()
方法返回的列表中的关键字值对。
结论
在本文中,我们看到了迭代字典中数据的各种方法。我们已经看到了如何使用 for 循环和内置方法如keys()
、values()
和items()
来访问字典的键和值。我们还可以使用 python try except 编写本文中使用的程序,以使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
Python 中的迭代器
原文:https://www.pythonforbeginners.com/basics/iterator-in-python
你一定在编程时使用过不同的数据结构,比如 python 字典、列表、元组和集合。我们经常需要按顺序访问这些数据结构的元素。
为了顺序地迭代这些数据结构,我们通常使用 for 循环和元素索引。在本文中,我们将尝试理解如何在不使用 for 循环或元素索引的情况下访问列表或元组的元素。
因此,让我们深入了解 Python 中迭代器和可迭代对象的概念。
Python 中什么是 iterable?
像列表或集合这样的容器对象可以包含许多元素。如果我们可以一次访问一个容器对象的成员元素,那么这个容器对象就叫做 iterable。在我们的程序中,我们使用不同的可重复项,如链表、元组、集合或字典。
使用 for 循环可以一次访问一个 iterable 的元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Elements of the list are:")
for element in myList:
print(element)
输出:
Elements of the list are:
1
2
3
4
5
6
7
8
9
10
在循环的中,我们从头到尾访问所有元素。但是,请考虑这样一种情况,只有在特定事件发生时,我们才需要访问 iterable 的下一个元素。
例如,让我们假设一个场景,其中我们有一个 100 个元素的列表。我们不断地要求用户输入一个数字,只要他们输入一个偶数,我们就打印列表的下一个元素。
现在,使用 for 循环无法做到这一点,因为我们无法预测用户何时会输入一个偶数。输入中没有顺序或次序会阻止我们在程序中使用 for 循环来迭代列表。在这种情况下,迭代器是访问可迭代元素的便利工具。那么,让我们学习什么是迭代器,以及如何用 python 创建迭代器来访问 iterable 的元素。
Python 中的迭代器是什么?
迭代器是可以被迭代的对象。换句话说,我们可以使用迭代器访问可迭代对象中的所有元素。
在 python 中,我们可以使用 iter()方法为任何容器对象创建迭代器。iter()方法接受一个 iterable 对象作为输入,并返回同一对象的迭代器。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myIter = iter(myList)
print("list is:", myList)
print("Iterator for the list is:", myIter)
输出:
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator for the list is: <list_iterator object at 0x7f4c21734070>
在输出中,您可以看到通过向 iter()函数传递一个列表创建了一个 list_iterator 对象。
如何在 Python 中遍历一个迭代器?
遍历迭代器最简单的方法是使用 for 循环。我们可以使用 for 循环访问迭代器中的每个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myIter = iter(myList)
print("list is:", myList)
print("Elements in the iterator are:")
for element in myIter:
print(element)
输出:
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements in the iterator are:
1
2
3
4
5
6
7
8
9
10
如前所述,如果我们没有遍历迭代器的顺序,for 循环将不起作用。对于这一点,我们可以用两种方法。
访问迭代器元素的第一种方法是使用 next()方法。当在迭代器上调用 next()方法时,它返回前一个遍历元素旁边的元素。它总是保留关于上次返回的元素的信息,并且每当它被调用时,它只返回尚未被遍历的下一个元素。我们可以通过下面的例子来理解这一点。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myIter = iter(myList)
print("list is:", myList)
print("Elements in the iterator are:")
try:
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
except StopIteration as e:
print("All elements in the iterator already traversed. Raised exception", e)
输出:
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements in the iterator are:
1
2
3
4
5
6
7
8
9
10
All elements in the iterator already traversed. Raised exception
访问迭代器元素的另一种方法是使用 next()函数。next()函数将迭代器作为输入,返回尚未遍历的下一个元素,就像 next()方法一样。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myIter = iter(myList)
print("list is:", myList)
print("Elements in the iterator are:")
try:
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
except StopIteration as e:
print("All elements in the iterator already traversed. Raised exception", e)
输出:
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements in the iterator are:
1
2
3
4
5
6
7
8
9
10
All elements in the iterator already traversed. Raised exception
从上面两个例子可以观察到 next()方法和 next()函数的功能几乎是相似的。此外,当迭代器的所有元素都已被遍历时,next()函数和 next()方法都会引发 StopIteration 错误。因此,建议使用除了块之外的 python try 来使用异常处理。
迭代器的用例示例
现在让我们仔细看看上面讨论的情况,只有当用户输入一个偶数时,我们才需要访问列表中的元素。
现在,我们有了 next()函数,无论何时调用该函数,它都可以从迭代器中访问元素。我们可以用它来访问列表中的元素。为此,我们将为列表创建一个迭代器,然后每当用户输入一个偶数时,我们将使用 next()函数访问列表中的元素。我们可以为此实现一个 python 函数,如下所示。
myList = range(0, 101)
myIter = iter(myList)
while True:
try:
user_input = int(input("Input an even number to get an output, 0 to exit:"))
if user_input == 0:
print("Good Bye")
break
elif user_input % 2 == 0:
print("Very good. Here is an output for you.")
print(next(myIter))
else:
print("Input an even number.")
continue
except StopIteration as e:
print("All the output has been exhausted.")
输出:
Input an even number to get an output, 0 to exit:1
Input an even number.
Input an even number to get an output, 0 to exit:2
Very good. Here is an output for you.
0
Input an even number to get an output, 0 to exit:4
Very good. Here is an output for you.
1
Input an even number to get an output, 0 to exit:3
Input an even number.
Input an even number to get an output, 0 to exit:6
Very good. Here is an output for you.
2
Input an even number to get an output, 0 to exit:0
Good Bye
结论
在本文中,我们讨论了如何使用 Python 中的迭代器从不同的可迭代对象中访问元素。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的关键字
原文:https://www.pythonforbeginners.com/basics/keywords-in-python
什么是关键词?
Python 中的关键字是保留字,不能用作普通的
标识符。它们的拼写必须与书写的完全一致。
关键词列表
以下是 Python 编程语言的关键词列表。
| 和 | 是吗 | 从 | 不 |
| 在…期间 | 如同 | 艾列弗 | 全球的 |
| 或者 | 随着 | 维护 | 其他 |
| 如果 | 及格 | 产量 | 破裂 |
| 除...之外 | 进口 | 打印 | 班级 |
| 高级管理人员 | 在 | 上升 | 继续 |
| 最后 | 是 | 返回 | 极好的 |
| 为 | 希腊字母的第 11 个 | 尝试 |
这将打印 Python 的关键字列表。
$ python
>>>
>>> import keyword
>>> print keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with',
'yield']
解释的关键字
打印
打印到控制台
而
控制着程序的流程
for
中断
中断(循环)循环,如果需要的话
继续
用来中断当前循环,而不跳出整个循环。
新的周期将开始。
如果用
来确定,哪些语句将要被执行。
elif
代表 else if。如果第一次测试评估为假,
则继续下一次测试
else
可选。else 关键字后的语句被执行,
除非条件为真
是
对对象身份的测试
not
否定一个布尔值
和
布尔表达式中的所有条件都必须满足
或
至少要满足一个条件。
导入
将其他模块导入到 Python 脚本中
as
如果我们想给一个模块一个不同的别名
中的用于从模块中导入特定的变量、类或函数
def
用于创建新的用户定义函数
返回
退出函数并返回值
λ
创建一个新的匿名函数
全局
访问函数外定义的变量
try
指定异常处理程序
except
捕捉异常并执行代码
最后
总是在最后被处决。用于清理资源。
引发
创建一个用户定义的异常
删除对象
过关
无所作为
断言
用于调试目的
类
用于创建新的用户定义对象
exec
动态执行 Python 代码
产量
与发电机一起使用
更多阅读
更详细的关键词解释和例子请见:
http://zetcode.com/lang/python/keywords/
Python 中的 Lambda 函数
原文:https://www.pythonforbeginners.com/basics/lambda-function-in-python
在编程时,我们可能会面临几种需要反复使用同一个数学语句的情况。在这种情况下,多次使用同一个语句会降低源代码的可读性。在本文中,我们将讨论如何使用 lambda 函数代替重复语句来消除 python 代码中的冗余。
Python 中的函数是什么?
python 中的函数是一组用于执行原子任务的语句。函数可以接受零个或多个参数,也可以返回值或对象。
例如,下面定义的 square()函数将一个数字作为输入参数,并将它的平方作为输出值返回。
def square(n):
return n ** 2
您可能会注意到,我们已经使用 def 语句定义了函数。相反,lambda 函数是使用 lambda 语句定义的。
Python 中的 Lambda 函数是什么?
lambda 函数类似于 python 中的函数。但是它有一些限制。
python 中的一个函数可以有多个语句,while loop、if-else 语句和其他编程构造来执行任何任务。另一方面,一个 lambda 函数只能有一条语句。
我们用 python 中的 lambda 关键字定义了一个 lambda 函数。声明 lambda 函数的语法如下。
myFunction = lambda [arguments]: expression
这里,
- “myFunction”是将使用此语句创建的 lambda 函数的名称。
- “lambda”是用于定义 lambda 函数的关键字。
- “Arguments”是 lambda 函数的参数。这里,我们将“参数”放在方括号[]中,因为 lambda 函数可能有也可能没有输入参数。
- “表达式”一般是数学表达式或者类似 print()的函数调用。
如何使用 Lambda 函数?
在 python 中,我们可以用 lambda 函数代替单行数学语句。例如,我们可以创建一个 lambda 函数,它接受一个数字并按如下方式计算其平方。
square = lambda n: n ** 2
print("Square of 4 is: ", square(4))
输出:
Square of 4 is: 16
使用 lambda 函数的另一种方法是减少代码中的冗余。例如,假设您需要计算四个数字的平方,并按如下方式一个接一个地打印它们的平方。
def square(n):
return n ** 2
print("Square of {} is:{} ".format(4, square(4)))
print("Square of {} is:{} ".format(3, square(3)))
print("Square of {} is:{} ".format(5, square(5)))
print("Square of {} is:{}".format(10, square(10)))
输出:
Square of 4 is:16
Square of 3 is:9
Square of 5 is:25
Square of 10 is:100
在这里,您可以观察到打印语句导致代码冗余。在这种情况下,我们可以创建一个 lambda 函数,它接受传递给 print 函数中 format()方法的输入参数。然后,我们可以使用这个 lambda 函数来删除代码中的冗余,如下所示。
def square(n):
return n ** 2
print_square = lambda x, y: print("Square of {} is:{} ".format(x, y))
print_square(4, square(4))
print_square(3, square(3))
print_square(5, square(5))
print_square(10, square(10))
输出:
Square of 4 is:16
Square of 3 is:9
Square of 5 is:25
Square of 10 is:100
结论
在本文中,我们讨论了 python 中的 lambda 函数。我们还看了一些可以在 python 中使用 lambda 函数的情况。我建议你阅读这篇关于 python 中的闭包的文章。
Python 中列表中最大的元素
原文:https://www.pythonforbeginners.com/basics/largest-element-in-a-list-in-python
我们经常使用列表来存储数字。在本文中,我们将讨论在 python 中查找列表中最大元素的不同方法。
使用 Python 中的 sort()方法的列表中最大的元素
如果列表被排序,最大的元素位于列表的末尾,我们可以使用语法list_name[-1]
来访问它。如果列表按降序排序,列表中最大的元素位于第一个位置,即索引 0。我们可以使用语法list_name[0]
来访问它。
当一个列表没有排序时,找到最大的数字是一个稍微不同的任务。在这种情况下,我们可以首先对列表进行排序,然后访问排序列表的最后一个元素。或者,我们可以检查列表中的每个元素,然后找到列表中最大的元素。
为了通过排序列表找到最大的元素,我们可以使用sort()
方法。当在列表上调用sort()
方法时,该方法按升序对列表进行排序。排序后,我们可以从 index -1 中得到列表的最大元素,如下所示。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myList.sort()
print("The maximum element in the list is:", myList[-1])
输出:
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
使用 sorted()方法查找列表中最大的元素
如果不允许对原始列表进行排序,可以使用sorted()
功能对列表进行排序。sorted()
函数将一个列表作为输入参数,并返回一个排序列表。获得排序后的列表后,我们可以在索引-1 处找到列表的最大元素,如下所示。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
newList = sorted(myList)
print("The maximum element in the list is:", newList[-1])
输出:
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
Python 中使用临时变量的列表中最大的元素
对一个列表进行排序需要O(n*log(n))
时间,其中 n 是列表中元素的数量。对于较大的列表,在我们获得最大的元素之前,可能要花很长时间对列表进行排序。使用另一种方法,我们可以在O(n)
时间内找到列表中最大的元素。
在这种方法中,我们将创建一个变量myVar
,并用列表的第一个元素初始化它。现在,我们将考虑myVar
具有最大的元素。之后,我们将比较myVar
和列表中的每个元素。如果发现任何元素大于myVar
,我们将用当前值更新myVar
中的值。遍历整个列表后,我们将在myVar
变量中获得列表的最大元素。您可以在下面的示例中观察到这一点。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myVar = myList[0]
for element in myList:
if element > myVar:
myVar = element
print("The maximum element in the list is:", myVar)
输出:
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
使用 Python 中的 max()函数的列表中最大的元素
代替上面的方法,你可以直接使用max()
函数来查找列表中最大的元素。max()
函数将列表作为输入参数,并返回列表中最大的元素,如下所示。
myList = [1, 23, 12, 45, 67, 344, 26]
print("The given list is:")
print(myList)
myVar = max(myList)
print("The maximum element in the list is:", myVar)
输出:
The given list is:
[1, 23, 12, 45, 67, 344, 26]
The maximum element in the list is: 344
结论
在本文中,我们讨论了在 python 中查找列表中最大元素的各种方法。要了解更多关于 python 中的列表,可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的集合理解的文章。
Python 中的左连接数据帧
原文:https://www.pythonforbeginners.com/basics/left-join-dataframes-in-python
左连接操作在 SQL 中用于连接两个表。在本文中,我们将讨论如何在 python 中对两个数据帧执行左连接操作。
什么是左连接运算?
假设我们有两个表 A 和 B。当我们执行操作(左连接 B)时,我们得到一个新表,它包含表 A 中的所有行以及表 B 中的相应行。除此之外,表 A 中与表 B 中没有任何匹配行的所有行也包含在输出表中。但是,属于表 B 的行,在表 A 中没有任何匹配的行,将从最终结果中忽略。
为了理解这一点,假设我们有一个包含学生详细信息的行的表 A,和一个包含学生成绩的行的表 B。同样,两个表有一个公共列,比如说 ‘Name’
。现在,如果我们想执行操作 A left join B,结果表将包含学生的详细信息以及他们的分数。此外,这些学生的详细信息将在输出表中提及,其分数不在表 b 中。相反,这些学生的分数将不包括在输出表中,其详细信息不在表 a 中。
由于数据帧包含表格数据,我们可以在 python 中对数据帧执行左连接操作。为此,我们将使用merge()
方法和join()
方法。
您可以使用以下链接下载程序中使用的文件。
使用 merge()方法左连接数据帧
我们可以使用 python 中的merge()
方法对数据帧执行左连接操作。为此,我们将在第一个数据帧上调用merge()
方法。此外,我们将把第二个数据帧作为第一个输入参数传递给merge()
方法。此外,我们将要匹配的列的名称作为输入参数传递给 ‘on’
参数,并将文字‘left’
作为输入参数传递给‘how’
参数。执行后, merge()
方法将返回输出数据帧,如下例所示。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
resultdf=names.merge(grades,how="left",on="Name")
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_x Roll_x Name Class_y Roll_y Grade
0 1 11 Aditya 1.0 11.0 A
1 1 12 Chris 1.0 12.0 A+
2 1 13 Sam NaN NaN NaN
3 2 1 Joel 2.0 1.0 B
4 2 22 Tom 2.0 22.0 B+
5 2 44 Samantha NaN NaN NaN
6 3 33 Tina 3.0 33.0 A-
7 3 34 Amy 3.0 34.0 A
如果第一个数据帧中的行在第二个数据帧中没有匹配的数据帧,这些行仍会包含在输出中。然而,对于在第一数据帧中没有任何匹配行的第二数据帧中的行来说,情况并非如此。你可以在上面的例子中观察到这一点。
如果有同名的列,python 解释器会给列名添加 _x
和_y
后缀。为了识别数据帧中调用了merge()
方法的列,添加了_x
后缀。对于作为输入参数传递给merge()
方法的 dataframe,使用了_y
后缀。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用 Join()方法左连接数据帧
不使用merge()
方法,我们可以使用 join()
方法在给定的数据帧上执行左连接操作。当在一个数据帧上调用 join()
方法时,它将另一个数据帧作为它的第一个输入参数。此外,我们将要匹配的列的名称作为输入参数传递给‘on’
参数,并将文字‘left’
作为输入参数传递给‘how’
参数。执行后, join()
方法返回输出数据帧,如下例所示。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
grades=grades.set_index("Name")
resultdf=names.join(grades,how="left",on="Name",lsuffix='_names', rsuffix='_grades')
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_names Roll_names Name Class_grades Roll_grades Grade
0 1 11 Aditya 1.0 11.0 A
1 1 12 Chris 1.0 12.0 A+
2 1 13 Sam NaN NaN NaN
3 2 1 Joel 2.0 1.0 B
4 2 22 Tom 2.0 22.0 B+
5 2 44 Samantha NaN NaN NaN
6 3 33 Tina 3.0 33.0 A-
7 3 34 Amy 3.0 34.0 A
在使用join()
方法时,您还需要记住,要执行连接操作的列应该是作为输入参数传递给join()
方法的 dataframe 的索引。如果数据帧的某些列有相同的列名,您需要使用lsuffix
和rsuffix
参数指定列名的后缀。如果列名相同,传递给这些参数的值可以帮助我们识别哪个列来自哪个数据帧。
结论
在本文中,我们讨论了在 python 中对数据帧执行左连接操作的两种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
Python 中的层次顺序树遍历
原文:https://www.pythonforbeginners.com/data-structures/level-order-tree-traversal-in-python
就像我们遍历一个 python 字典、一个列表或元组来访问它的元素一样,我们也可以遍历二叉树来访问它们的元素。有四种树遍历算法,即按序树遍历、前序树遍历、后序树遍历和层次序树遍历。在本文中,我们将讨论层次顺序树遍历算法,并用 python 实现它。
什么是层次顺序树遍历?
层次顺序树遍历算法是一种广度优先的树遍历算法。这意味着在遍历树时,我们首先遍历当前层的所有元素,然后再移动到下一层。为了理解这个概念,让我们考虑下面的二叉查找树。
上述树的层次顺序遍历如下。
我们将从根开始,打印 50 个。之后,我们移动到下一个级别,打印 20 和 53。在这一层之后,我们移动到另一层,打印 11、22、52 和 78。因此,上述树的层次顺序遍历是 50,20,53,11,22,52,78。
层次顺序树遍历算法
正如我们已经看到的,我们必须在层次顺序树遍历中一个接一个地处理每个层次上的元素,我们可以使用下面的方法。我们将从根节点开始,并打印它的值。之后,我们将把根节点的两个子节点移动到一个队列中。该队列将用于包含接下来必须处理的元素。每当我们处理一个元素时,我们会将该元素的子元素放入队列中。这样,同一级别的所有元素将以连续的顺序被推入队列,并以相同的顺序被处理。
层级顺序树遍历的算法可以用公式表示如下。
- 定义一个队列 Q 来包含元素。
- 将根插入 q。
- 从 q 中取出一个节点。
- 如果节点为空,即无,转到 8。
- 打印节点中的元素。
- 将当前节点的左子节点插入 q。
- 将当前节点的右子节点插入 q。
- 检查 Q 是否为空。如果是,停止。否则,转到 3。
层次顺序树遍历算法在 Python 中的实现
现在我们将用 python 实现上述算法。之后,我们将使用相同的算法处理上述示例中使用的二叉查找树。
from queue import Queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def levelorder(root):
Q = Queue()
Q.put(root)
while (not Q.empty()):
node = Q.get()
if node == None:
continue
print(node.data)
Q.put(node.leftChild)
Q.put(node.rightChild)
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# if newValue is less than value of data in root, add it to left subtree and proceed recursively
if newValue < root.data:
root.leftChild = insert(root.leftChild, newValue)
else:
# if newValue is greater than value of data in root, add it to right subtree and proceed recursively
root.rightChild = insert(root.rightChild, newValue)
return root
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Level Order traversal of the binary tree is:")
levelorder(root)
输出:
Level Order traversal of the binary tree is:
50
20
53
11
22
52
78
在上面的程序中,我们首先实现了图中给出的二叉查找树。然后,我们使用层次顺序树遍历算法来遍历 Python 中的二叉查找树。正如您所看到的,程序使用了一个队列来存储要处理的数据。此外,二叉查找树的元素按照它们在树中的深度顺序从左到右打印。首先打印根节点,最后打印叶节点。
结论
在本文中,我们讨论了 Python 中的层次顺序树遍历算法。层次顺序树遍历可以用来在 Python 中找到二叉树的宽度。此外,该算法还被用于实现其他各种算法,我们将在本系列的后面讨论这些算法。在接下来的文章中,我们将实现其他的树遍历算法,比如有序树遍历、前序树遍历和后序树遍历算法。要了解更多关于其他数据结构的知识,可以阅读这篇关于 Python 中的链表的文章。请继续关注更多关于用 Python 实现不同算法的文章。
Python 中的线性搜索
原文:https://www.pythonforbeginners.com/basics/linear-search-in-python
在编程的时候,你一定遇到过我们需要知道一个元素在列表中的位置的情况。为此,我们可以使用线性搜索算法。在本文中,我们将实现一个线性搜索算法,在 python 中查找列表中元素的索引。
什么是线性搜索算法?
在线性搜索算法中,我们从列表的索引 0 开始,检查元素是否出现在索引处。如果元素出现在索引处,我们将索引作为输出返回。否则,我们移动到下一个索引,直到我们找到正在被搜索的元素或者到达列表的末尾。
例如,假设给我们一个列表myList=[1,23,45,23,34,56,12,45,67,24]
。
现在,我们要搜索元素 12 的索引。为此,我们将从索引 0 开始,检查 12 是否存在。如果是,我们将返回 0 作为结果,或者我们将移动到索引 1。我们将继续以这种方式移动到索引 6,其中有 12。在检查索引 6 处是否存在 12 之后,我们将返回 6 作为输出。如果任何元素不存在,我们将返回-1,这将指定该元素不在列表中。
有了线性搜索操作的概述,让我们定义线性搜索操作的算法。
线性搜索算法
线性搜索的算法可以指定如下。
算法输入:一个列表和一个要搜索的元素。
输出:元素的索引(如果元素存在的话)。否则为-1。
- 从列表的索引 0 开始。
- 检查元素是否出现在当前位置。
- 如果是,返回当前索引。转到 8。
- 检查当前元素是否是列表的最后一个元素。
- 如果是,返回-1。转到 8。否则,转到 6。
- 移动到列表的下一个索引。
- 转到 2。
- 停下来。
因为我们已经定义了线性搜索的算法,所以让我们用 python 实现它。
def LinearSearch(input_list: list, element: int):
list_len = len(input_list)
for i in range(list_len):
if input_list[i] == element:
return i
return -1
myList = [1, 23, 45, 23, 34, 56, 12, 45, 67, 24]
print("Given list is:", myList)
position = LinearSearch(myList, 12)
print("Element 12 is at position:", position)
输出:
Given list is: [1, 23, 45, 23, 34, 56, 12, 45, 67, 24]
Element 12 is at position: 6
线性搜索算法的缺点
线性搜索算法在时间复杂度方面是非常昂贵的。在最坏的情况下,它具有 O(n)复杂度,其中 n 是列表中元素的数量。
另一个缺点是它没有考虑列表中元素的排列。如果元素按升序排列,并且我们必须搜索最大的元素,则总是需要最大数量的步骤来产生结果。
类似地,如果一个元素不在列表中,当它遍历列表中的每个元素时,它将再次花费最大数量的步骤来产生结果。
结论
在本文中,我们讨论了线性搜索算法。我们也用 python 实现了它。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的链表
原文:https://www.pythonforbeginners.com/lists/linked-list-in-python
链表是一种数据结构,它包含由链接连接的数据对象。每个链表由具有数据字段和对链表中下一个节点的引用的节点组成。在本文中,我们将研究链表背后的基本概念,并用 python 实现它。
链表中的节点是什么?
节点是一个对象,它有一个数据字段和一个指向链表中另一个节点的指针。下图显示了一个简单的节点结构。
Node of a linked list in python
我们可以使用具有两个字段(即 data 和 next)的类节点来实现上述对象,如下所示。
class Node:
def __init__(self,data):
self.data=data
self.next=None
链表由许多这样的节点组成。链表中有一个头指针指向链表中的第一个节点,或者当链表为空时没有头指针。下图描述了一个有三个节点的链表。
Linked list in python
我们可以看到最后一个节点的 next 字段指向 None,引用头指向第一个节点。空链表将是一个头指针指向 None 的链表。可以用 python 创建一个空链表,如下所示。
class linkedList:
def __init__(self):
self.head=None
向链表中插入元素
我们可以在链表中的第一个位置、最后一个位置或者两者之间的任何位置插入一个元素。
为了在链表的开头插入一个元素,我们将首先用给定的数据创建一个节点,并将它的下一个引用分配给第一个节点,也就是头指向的地方。然后,我们将 head 引用指向新节点。为了执行这个操作,我们如下实现方法 insertAtBeginning。
def insertAtBeginning(self,data):
temp=Node(data)
if self.head==None:
self.head=temp
else:
temp.next=self.head
self.head=temp
要在链表的末尾插入一个元素,我们只需要找到下一个元素没有引用的节点,即最后一个节点。然后,我们用给定的数据创建一个新节点,并将最后一个节点的下一个元素指向新创建的节点。为了执行这个操作,我们如下实现方法 insertAtEnd。
def insertAtEnd(self,data):
temp=Node(data)
if self.head==None:
self.head=temp
else:
curr=self.head
while curr.next!=None:
curr=curr.next
curr.next=temp
要在任何其他给定位置插入元素,我们可以计算节点数,直到到达该位置,然后将新节点的下一个元素指向当前节点的下一个节点,并将当前节点的下一个引用指向新节点。这可以使用 insertAtGivenPosition 方法实现,如下所示。
def insertAtGivenPosition(self,data,position):
count=1
curr=self.head
while count<position-1 and curr!=None:
curr=curr.next
count+=1
temp=Node(data)
temp.next=curr.next
curr.next=temp
遍历链表
为了遍历 python 中的链表,我们将从头开始,打印数据并移动到下一个节点,直到到达 None,即链表的末尾。下面的 traverse()方法实现了在 python 中遍历链表的程序。
def traverse(self):
curr=self.head
while curr!=None:
print(curr.data)
curr=curr.next
删除节点
我们可以从链表的开始或者结束或者两个节点之间删除一个节点。
要删除链表的第一个节点,我们将首先检查链表的头是否指向 None,如果是,那么我们将使用 python try except 抛出一个异常,并显示一条消息,说明链表为空。否则,我们将删除 head 引用的当前节点,并将 head 指针移动到下一个节点。这可以如下实现。
def delFromBeginning(self):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
temp=self.head
self.head=self.head.next
del temp
except Exception as e:
print(str(e))
为了删除链表的最后一个节点,我们将遍历链表中的每个节点,并检查当前节点的下一个节点的 next 指针是否指向 None,如果是,则当前节点的下一个节点是最后一个节点,它将被删除。这可以如下实现。
def delFromEnd(self):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
curr=self.head
prev=None
while curr.next!=None:
prev=curr
curr=curr.next
prev.next=curr.next
del curr
except Exception as e:
print(str(e))
要删除链表之间的节点,在每一个节点,我们将检查下一个节点的位置是否是要删除的节点,如果是,我们将删除下一个节点,并将下一个引用分配给要删除的节点的下一个节点。这可以如下进行。
def delAtPos(self,position):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
curr=self.head
prev=None
count=1
while curr!=None and count<position:
prev=curr
curr=curr.next
count+=1
prev.next=curr.next
del curr
except Exception as e:
print(str(e))
下面是用 python 实现链表的 python 代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 24 18:28:15 2021
@author: aditya1117
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head=None
def insertAtBeginning(self,data):
temp=Node(data)
if self.head==None:
self.head=temp
else:
temp.next=self.head
self.head=temp
def insertAtEnd(self,data):
temp=Node(data)
if self.head==None:
self.head=temp
else:
curr=self.head
while curr.next!=None:
curr=curr.next
curr.next=temp
def insertAtGivenPosition(self,data,position):
count=1
curr=self.head
while count<position-1 and curr!=None:
curr=curr.next
count+=1
temp=Node(data)
temp.next=curr.next
curr.next=temp
def traverse(self):
curr=self.head
while curr!=None:
print(curr.data)
curr=curr.next
def delFromBeginning(self):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
temp=self.head
self.head=self.head.next
del temp
except Exception as e:
print(str(e))
def delFromEnd(self):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
curr=self.head
prev=None
while curr.next!=None:
prev=curr
curr=curr.next
prev.next=curr.next
del curr
except Exception as e:
print(str(e))
def delAtPos(self,position):
try:
if self.head==None:
raise Exception("Empty Linked List")
else:
curr=self.head
prev=None
count=1
while curr!=None and count<position:
prev=curr
curr=curr.next
count+=1
prev.next=curr.next
del curr
except Exception as e:
print(str(e))
结论
在这篇文章中,我们研究了链表并在 python 中实现了它。您可能已经观察到链表与内置数据结构(如 python dictionary 、list 和 set e.t.c)的不同之处。请复制工作代码并对其进行实验,以获得更多见解。请继续关注更多内容丰富的文章。
Python 中的列表理解
原文:https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
作为 Python 程序员,您可能会使用很多列表。虽然我们都是 for 循环(和嵌套 for 循环)的忠实粉丝,但 Python 提供了一种更简洁的方法来处理列表和列表理解。
为了保持代码的优雅和可读性,建议您使用 Python 的理解特性。
列表理解是在 Python 中创建列表的一种强大而简洁的方法,当您使用列表和列表列表时,它变得必不可少。
句法
考虑下面的例子:
列表中项目的 my_new_list = [ 表达式
从这个例子中可以看出,理解 python 列表需要三个要素。
- 首先是我们想要执行的表达式。方括号内的表达式。
- 第二个是表达式将处理的对象。方括号内的项目。
- 最后,我们需要一个可迭代的对象列表来构建我们的新列表。在方括号内列出。
要理解列表理解,想象一下:你要对列表中的每一项执行一个表达式。表达式将决定最终在输出列表中存储什么项目。
您不仅可以在一行代码中对整个列表执行表达式,而且,正如我们将在后面看到的,还可以以过滤器的形式添加条件语句,这使得处理列表的方式更加精确。
关于列表理解的注记
- 列表理解方法是一种创建和管理列表的优雅方式。
- 在 Python 中,列表理解是一种更紧凑的创建列表的方式。
- 比循环更灵活,列表理解通常比其他方法更快。
创建范围为()的列表
让我们从使用 Python list comprehensions 创建一个数字列表开始。我们将利用 Python 的 range() 方法来创建一个数字列表。
示例 1:创建具有列表理解的列表
# construct a basic list using range() and list comprehensions
# syntax
# [ expression for item in list ]
digits = [x for x in range(10)]
print(digits)
输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
让我们从第一个“x”开始分解这个 python 例子。这是我们的表达方式。它没有做任何事情,因为我们只是记录数字。第二个“x”代表由 range() 方法创建的列表中的每一项。
在上面的 python 例子中,我们使用了 range() 方法来生成一个数字列表。 Python 遍历(或循环)该范围内的每一项,并将该项的副本保存在一个名为 digits 的新列表中。
也许这似乎是多余的?那只是因为你还没有看到理解列表的真正潜力。
使用 Python 中的循环和列表理解创建列表
为了更好地说明如何使用列表理解来编写更高效的 Python 代码,我们来看一下并排比较。
在以下示例中,您将看到创建 Python 列表的两种不同技术。第一个是 for 循环。我们将用它来构造一个 2 的幂的列表。
示例 2:比较 Python 中的列表创建方法
首先,创建一个列表并遍历它。添加一个表达式,在这个例子中,我们将 x 提高到 2 的幂。
# create a list using a for loop
squares = []
for x in range(10):
# raise x to the power of 2
squares.append(x**2)
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
输出
使用 list comprehension 可以做同样的事情,但是只需要一部分代码。让我们来看看如何使用列表理解方法创建一个正方形列表。
# create a list using list comprehension
squares = [x**2 for x in range(10)]
print(squares)
即使在这个基本的例子中,很明显列表理解减少了处理列表时完成复杂任务所需的代码。
列表的乘法部分
如果我们想用 Python 把列表中的每个数字都乘以 3 会怎么样?我们可以写一个 for 循环并将结果存储在一个新的列表中,或者我们可以使用列表理解。
例 3:列表综合乘法
# create a list with list comprehensions
multiples_of_three = [ x*3 for x in range(10) ]
print(multiples_of_three)
输出
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
通过利用列表理解,可以只处理列表的一部分。例如,如果您只想要给定范围内的偶数,您可以使用过滤器找到它们。
向列表理解添加过滤器允许更大的灵活性。通过使用过滤器,我们可以从列表中选择某些项目,同时排除其他项目。这是 Python 中列表的一个高级特性。
even_numbers = [ x for x in range(1,20) if x % 2 == 0]
输出
[2, 4, 6, 8, 10, 12, 14, 16, 18]
使用 Python 显示每个单词的首字母
到目前为止,我们已经看到了用 Python 构建数字列表的例子。接下来,让我们尝试使用字符串和列表理解的各种方法来优雅地处理字符串列表。
示例 4:使用带有字符串的列表理解
# a list of the names of popular authors
authors = ["Ernest Hemingway","Langston Hughes","Frank Herbert","Toni Morrison",
"Emily Dickson","Stephen King"]
# create an acronym from the first letter of the author's names
letters = [ name[0] for name in authors ]
print(letters)
输出
['E', 'L', 'F', 'T', 'E', 'S']
使用简化的表达式,列表理解可以使解决涉及字符串的问题更加容易。这些方法可以节省时间和宝贵的代码行。
示例 5:分隔字符串中的字符
# use list comprehension to print the letters in a string
letters = [ letter for letter in "20,000 Leagues Under The Sea"]
print(letters)
输出
['2', '0', ',', '0', '0', '0', ' ', 'L', 'e', 'a', 'g', 'u', 'e', 's', ' ', 'U', 'n', 'd', 'e', 'r', ' ', 'T', 'h', 'e', ' ', 'S', 'e', 'a']
使用 Python 的小写/大写转换器
使用 list comprehension 遍历 Python 中的字符串,可以将字符串从小写转换为大写,反之亦然。
利用 Python 的 lower() 和 upper() 方法,我们将使用列表理解来实现这个常见任务。
示例 6:改变字母的大小写
lower_case = [ letter.lower() for letter in ['A','B','C'] ]
upper_case = [ letter.upper() for letter in ['a','b','c'] ]
print(lower_case, upper_case)
输出
['a', 'b', 'c'] ['A', 'B', 'C']
仅打印给定字符串中的数字
另一个有趣的练习是从字符串中提取数字。例如,我们可能有一个姓名和电话号码的数据库。
如果我们能把电话号码和名字分开会很有用。使用列表理解,我们可以做到这一点。
利用 Python 的 isdigit() 方法,我们可以从用户数据中提取出电话号码。
示例 7:使用 isdigit()方法识别字符串中的数字
# user data entered as name and phone number
user_data = "Elvis Presley 987-654-3210"
phone_number = [ x for x in user_data if x.isdigit()]
print(phone_number)
输出
['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']
使用列表理解解析文件
也可以使用列表理解来读取 Python 中的文件。为了演示,我创建了一个名为 dreams.txt 的文件,并粘贴了下面的文本,一首兰斯顿·休斯的短诗。
紧紧抓住梦想,因为如果梦想消亡,生活就像折断翅膀的鸟儿
再也不能飞翔。兰斯顿·休斯
使用列表理解,我们可以遍历文件中的文本行,并将它们的内容存储在一个新的列表中。
例 8:阅读一首带有列表理解的诗
# open the file in read-only mode
file = open("dreams.txt", 'r')
poem = [ line for line in file ]
for line in poem:
print(line)
输出
Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
-Langston Hughs
在列表理解中使用函数
到目前为止,我们已经看到了如何使用 list comprehension 使用一些基本的 Python 方法生成列表,如 lower() 和 upper() 。但是如果我们想使用自己的 Python 函数呢?
我们不仅可以用列表理解来编写自己的函数,还可以添加过滤器来更好地控制语句。
例 9:为列表理解添加参数
# list comprehension with functions
# create a function that returns a number doubled
def double(x):
return x*2
nums = [double(x) for x in range(1,10)]
print(nums)
输出
[2, 4, 6, 8, 10, 12, 14, 16, 18]
可以使用附加参数从列表中过滤元素。在下面的示例中,只选择了偶数。
# add a filter so we only double even numbers
even_nums = [double(x) for x in range(1,10) if x%2 == 0]
print(even_nums)
输出
[4, 8, 12, 16]
可以添加其他参数来创建更复杂的逻辑:
nums = [x+y for x in [1,2,3] for y in [10,20,30]]
print(nums)
输出
[11, 21, 31, 12, 22, 32, 13, 23, 33]
最后
希望您已经看到了列表理解的潜力,以及如何使用它们来编写更优雅的 Python 代码。编写紧凑的代码对于维护程序和与团队合作是必不可少的。
学会利用像列表理解这样的高级功能可以节省时间,提高效率。
当你的 Python 代码更加简洁易读时,不仅你的同事会感谢你,而且当你回到一个你几个月都没做的程序,代码是可管理的时候,你也会感谢你自己。
相关职位
有兴趣了解更多关于 Python 编程的知识吗?请点击这些链接,获取将对您的 Python 之旅有所帮助的其他资源。
- 了解一个单独的 Python 注释是如何改进程序的。
- 探索 Python 字符串串联
Python 中 CSV 格式的词典列表
原文:https://www.pythonforbeginners.com/basics/list-of-dictionaries-to-csv-in-python
我们在 python 中使用字典来存储键值对。类似地,我们使用 CSV 文件来存储包含特定字段值的记录。在本文中,我们将讨论如何用 python 将词典列表转换成 CSV 文件。
使用 csv.writer()在 Python 中将字典列表转换为 CSV
csv 模块为我们提供了对 CSV 文件执行各种操作的不同方法。要在 python 中将字典列表转换成 csv 格式,我们可以使用csv.writer()
方法和csv.writerow()
方法。为此,我们将使用以下步骤。
- 首先,我们将使用
open()
函数以写模式打开一个 csv 文件。open()
函数将文件名作为第一个输入参数,将文字“w”作为第二个输入参数,以表明文件将以写模式打开。它返回一个 file 对象,包含由open()
函数创建的空 csv 文件。 - 打开文件后,我们将使用
csv.writer()
方法创建一个csv.writer
对象。csv.writer()
方法将 file 对象作为输入参数,并返回一个 writer 对象。一旦创建了 writer 对象,我们就可以使用csv.writerow()
方法将字典列表中的数据添加到 csv 文件中。 - 在 writer 对象上调用
csv.writerow()
方法时,该方法获取一个值列表,并将其添加到 writer 对象引用的 csv 文件中。 - 首先,我们将通过向 csv 文件添加字典的键来添加 CSV 文件的头。
- 添加头之后,我们将使用一个带有
writerow()
方法的 for 循环来将每个字典添加到 csv 文件中。这里,我们将把字典中的值传递给 CSV 文件。
在执行 for 循环后,来自 python 字典的数据将被添加到 CSV 文件中。要保存数据,您应该使用close()
方法关闭文件。否则,不会将任何更改保存到 csv 文件中。
使用csv.writer()
方法将字典列表转换成 csv 文件的源代码如下。
import csv
listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
{'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
myFile = open('demo_file.csv', 'w')
writer = csv.writer(myFile)
writer.writerow(['Name', 'Roll', 'Language'])
for dictionary in listOfDict:
writer.writerow(dictionary.values())
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()
输出:
THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript
使用 csv 将字典列表转换为 Python 中的 CSV。词典作者()
我们可以一次将整个词典列表转换为 csv 文件,而不是使用迭代方法将每个词典添加到 CSV 文件中。为此,我们将使用DictWriter()
方法和csv.writerows()
方法。
这种方法在以下几个步骤上不同于前面的方法。
- 我们将使用
Dictwriter()
方法创建一个csv.DictWriter
对象,而不是创建一个 csv.writer 对象。DictWriter()
方法将包含 csv 文件的 file 对象作为第一个参数,将 csv 文件的列名作为第二个输入参数。执行后,它返回一个DictWriter
对象。 - 创建完 DictWriter 对象后,我们将把头文件添加到 csv 文件中。为此,我们将使用
writeheader()
方法。当在一个DictWriter
对象上执行时,writeheader()
方法添加提供给DictWriter()
方法的列作为 csv 文件的标题。 - 添加头之后,我们可以使用
writerows()
方法将整个词典列表添加到 csv 文件中。当在一个DictWriter
对象上调用时,writerows()
方法将一个字典列表作为其输入参数,并将字典中的值添加到 csv 文件中。
将整个词典列表添加到 csv 文件后,必须使用close()
方法关闭该文件。否则,不会保存任何更改。
下面给出了用 python 将字典列表转换成 csv 文件的源代码。
import csv
listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
{'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
myFile = open('demo_file.csv', 'w')
writer = csv.DictWriter(myFile, fieldnames=['Name', 'Roll', 'Language'])
writer.writeheader()
writer.writerows(listOfDict)
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()
输出:
THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript
结论
在本文中,我们讨论了用 python 将词典列表转换成 csv 文件的两种方法。在这些方法中,每个字典都将被添加到 csv 文件中,而不管它与 csv 文件中的列相比是否具有相同的项目数,或者与 csv 文件中的列名相比是否具有相同的键。因此,建议确保每本词典都有相同数量的条目。此外,您应该确保字典中的键的顺序应该相同。否则,附加到 csv 文件的数据将变得不一致,并会导致错误。
想了解更多 python 中的字典,可以阅读这篇关于 python 中字典理解的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
Python 中数据帧的字典列表
原文:https://www.pythonforbeginners.com/basics/list-of-dictionaries-to-dataframe-in-python
在 python 中,数据帧主要用于分析表格数据。在本文中,我们将讨论如何用 python 将字典列表转换成数据帧。
使用熊猫数据框的字典列表。DataFrame
()
dataframe 对象在 pandas 模块中定义。为了从给定的字典列表中创建一个数据帧,我们可以使用 DataFrame()
方法。DataFrame()
方法对象将字典列表作为输入参数,并返回从字典创建的 dataframe。这里,数据帧的列名由 python 字典中的键组成。每个字典的值被转换成数据帧的行。您可以使用 pandas.DataFrame()
方法从字典列表中创建一个数据帧,如下所示。
import pandas as pd
listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
{'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame(listOfDict)
print("The dataframe is:")
print(df)
输出:
THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
在数据帧中,为字典列表中的每个关键字创建一列。如果一个字典没有任何特定的键,则值NaN
被赋予对应于代表该字典的行中的特定键的列。
使用 pandas.dataframe.from_dict()方法将字典列表转换为 Python 中的数据帧
除了使用DataFrame()
方法,我们还可以使用from_dict()
方法将字典列表转换成 Python 中的数据帧。from_dict()
方法将一个字典列表作为其输入参数,并返回一个 dataframe。同样,数据帧的列名由字典中的键组成。每个字典的值被转换成数据帧的行。您可以使用from_dict()
方法从字典列表中创建一个数据帧,如下所示。
import pandas as pd
listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
{'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame.from_dict(listOfDict)
print("The dataframe is:")
print(df)
输出:
THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
您可以观察到由 from_dict()方法生成的 dataframe 类似于由 dataframe()方法生成的 DataFrame。
使用 pandas . Dataframe . from _ records(Data)将字典列表转换为 Data frame
为了从 Python 中的字典列表创建一个 dataframe,我们也可以使用from_records()
方法。from_records()
方法将字典列表作为其输入参数,并返回一个 dataframe。同样,数据帧的列名由字典中的键组成。每个字典的值被转换成数据帧的行。您可以使用from_records()
方法从字典列表中创建一个数据帧,如下所示。
import pandas as pd
listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
{'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame.from_records(listOfDict)
print("The dataframe is:")
print(df)
输出:
THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
结论
在本文中,我们讨论了用 python 将字典列表转换成数据帧的三种方法。这三种方法在语义上是相似的,并且产生相同的结果。要了解更多关于字典的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
Python 中的列表列表
原文:https://www.pythonforbeginners.com/basics/list-of-lists-in-python
当我们需要顺序访问数据时,python 中使用列表来存储数据。在本文中,我们将讨论如何用 python 创建一个列表列表。我们还将实现一些程序来执行各种操作,比如在 python 中对列表进行排序、遍历和反转。
Python 中的列表列表是什么?
python 中的列表列表是包含列表作为其元素的列表。下面是一个列表的例子。
myList=[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
这里,myList
包含五个列表作为其元素。因此,它是一个列表列表。
用 Python 创建一个列表列表
要在 python 中创建一个列表列表,可以使用方括号来存储所有内部列表。例如,如果您有 5 个列表,并且您想从给定的列表中创建一个列表,您可以将它们放在方括号中,如下面的 python 代码所示。
list1 = [1, 2, 3, 4, 5]
print("The first list is:", list1)
list2 = [12, 13, 23]
print("The second list is:", list2)
list3 = [10, 20, 30]
print("The third list is:", list3)
list4 = [11, 22, 33]
print("The fourth list is:", list4)
list5 = [12, 24, 36]
print("The fifth list is:", list5)
myList = [list1, list2, list3, list4, list5]
print("The list of lists is:")
print(myList)
输出:
The first list is: [1, 2, 3, 4, 5]
The second list is: [12, 13, 23]
The third list is: [10, 20, 30]
The fourth list is: [11, 22, 33]
The fifth list is: [12, 24, 36]
The list of lists is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
在上面的例子中,您可以观察到我们已经使用给定的列表创建了一个列表列表。
Python 中使用 append()方法的列表列表
我们还可以使用 python 中的append()
方法创建一个列表列表。在列表上调用append()
方法时,该方法将一个对象作为输入,并将其附加到列表的末尾。为了使用append()
方法创建一个列表列表,我们将首先创建一个新的空列表。为此,您可以使用方括号符号或list()
构造函数。list()
构造函数在没有输入参数的情况下执行时,返回一个空列表。
创建空列表后,我们可以使用append()
方法将所有给定的列表添加到创建的列表中,以创建 python 中的列表列表,如下面的代码片段所示。
list1 = [1, 2, 3, 4, 5]
print("The first list is:", list1)
list2 = [12, 13, 23]
print("The second list is:", list2)
list3 = [10, 20, 30]
print("The third list is:", list3)
list4 = [11, 22, 33]
print("The fourth list is:", list4)
list5 = [12, 24, 36]
print("The fifth list is:", list5)
myList = []
myList.append(list1)
myList.append(list2)
myList.append(list3)
myList.append(list4)
myList.append(list5)
print("The list of lists is:")
print(myList)
输出:
The first list is: [1, 2, 3, 4, 5]
The second list is: [12, 13, 23]
The third list is: [10, 20, 30]
The fourth list is: [11, 22, 33]
The fifth list is: [12, 24, 36]
The list of lists is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
如果你想创建一个类似于二维数组的列表,只使用整数数据类型,你可以使用嵌套的 for 循环和append()
方法来创建一个列表列表。
在这种方法中,我们将首先创建一个新的列表,比如说myList
。之后,我们将使用嵌套的 for 循环将其他列表追加到myList
中。在嵌套循环的外部 for 循环中,我们将创建另一个空列表,比如说tempList
。在内部 for 循环中,我们将使用append()
方法将数字附加到tempList
。
在将数字附加到tempList
之后,我们将得到一个整数列表。之后,我们将进入外部 for 循环,并将tempList
追加到myList
。这样,我们可以创建一个列表列表。
例如,假设我们必须创建一个 3×3 的数字数组。为此,我们将使用range()
函数和 for 循环来创建 python 中的列表列表,如下所示。
myList = []
for i in range(3):
tempList = []
for j in range(3):
element = i + j
tempList.append(element)
myList.append(tempList)
print("The list of lists is:")
print(myList)
输出:
The list of lists is:
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
使用 Python 中的列表理解创建列表列表
不使用 for 循环,你可以使用列表理解和range()
函数以简洁的方式创建一个列表列表,如下例所示。
myList = [[i+j for i in range(3)] for j in range(3)]
print("The list of lists is:")
print(myList)
输出:
The list of lists is:
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
在 Python 中访问列表列表中的元素
我们可以使用列表索引来访问列表的内容。在平面列表或一维列表中,我们可以使用元素的索引直接访问列表元素。例如,如果我们想使用正值作为列表元素的索引,我们可以使用索引 0 访问列表的第一项,如下所示。
myList = [1, 2, 3, 4, 5]
print("The list is:")
print(myList)
print("The first item of the list is:")
print(myList[0])
输出:
The list is:
[1, 2, 3, 4, 5]
The first item of the list is:
1
类似地,如果我们使用负值作为列表索引,我们可以使用 index -1 访问列表的最后一个元素,如下所示。
myList = [1, 2, 3, 4, 5]
print("The list is:")
print(myList)
print("The last item of the list is:")
print(myList[-1])
输出:
The list is:
[1, 2, 3, 4, 5]
The last item of the list is:
5
如果你想从一个列表的列表中访问内部列表,你可以像上面的例子一样使用列表索引。
如果使用正数作为列表索引,可以使用索引 0 访问列表中的第一个内部列表,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The list of lists is:")
print(myList)
print("The first item of the nested list is:")
print(myList[0])
输出:
The list of lists is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The first item of the nested list is:
[1, 2, 3, 4, 5]
类似地,如果您使用负数作为列表索引,您可以从列表列表中访问最后一个内部列表,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The list of lists is:")
print(myList)
print("The last item of the nested list is:")
print(myList[-1])
输出:
The list of lists is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The last item of the nested list is:
[12, 24, 36]
要访问内部列表的元素,需要在列表名称后使用双方括号。这里,第一个方括号表示内部列表的索引,第二个方括号表示内部列表中元素的索引。
例如,您可以使用方括号从列表列表中访问第二个列表的第三个元素,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The list of lists is:")
print(myList)
print("The third element of the second inner list is:")
print(myList[1][2])
输出:
The list of lists is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The third element of the second inner list is:
23
在 Python 中遍历列表列表
若要遍历列表列表的元素,我们可以将用于循环。要打印内部列表,我们可以简单地遍历列表列表,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
for inner_list in myList:
print(inner_list)
输出:
[1, 2, 3, 4, 5]
[12, 13, 23]
[10, 20, 30]
[11, 22, 33]
[12, 24, 36]
我们也可以打印列表的元素,而不是在遍历列表时打印整个列表。为此,除了前面示例中显示的 For 循环之外,我们还将使用另一个 for 循环。在内部 for 循环中,我们将遍历内部列表并打印它们的元素,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
for inner_list in myList:
for element in inner_list:
print(element, end=",")
print("")
输出:
1,2,3,4,5,
12,13,23,
10,20,30,
11,22,33,
12,24,36,
在 Python 中从列表列表中删除元素
要从一个列表中删除一个内部列表,我们可以使用不同的 list-objects 方法。
使用 pop()方法从列表中删除一个元素
我们可以使用pop()
方法删除列表中的最后一项。当在列表列表上调用pop()
方法时,删除最后一个元素并返回最后一个位置的列表。我们可以通过下面一个简单的例子来理解这一点。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.pop()
print("The modified list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The modified list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33]]
要删除任何其他内部列表,我们需要知道它的索引。例如,我们可以使用pop()
方法删除列表的第二个元素。为此,我们将调用列表上的pop()
方法,并将第二个列表的索引(即 1)传递给 pop()
方法。执行后,pop()
方法将从列表列表中删除第二个内部列表,并返回它,如下例所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.pop(1)
print("The modified list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The modified list is:
[[1, 2, 3, 4, 5], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
使用 Remove()方法从列表列表中移除元素
如果我们知道必须删除的元素,我们也可以使用remove()
方法删除一个内部列表。当在列表上调用时,remove()
方法将待删除的元素作为其输入参数。执行后,它删除作为输入参数传递的元素的第一个匹配项。要删除任何内部列表,我们可以使用如下所示的remove()
方法。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.remove([1, 2, 3, 4, 5])
print("The modified list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The modified list is:
[[12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
Python 中的扁平化列表
有时,我们需要将一系列列表扁平化来创建一个一维列表。为了使列表变平,我们可以使用 for 循环和append()
方法。在这种方法中,我们将首先创建一个空列表,比如说outputList
。
在创建了outputList
之后,我们将使用一个嵌套的 for 循环来遍历列表的列表。在外部 for 循环中,我们将选择一个内部列表。之后,我们将在内部 for 循环中遍历内部列表的元素。在内部 for 循环中,我们将调用outputList
上的append()
方法,并将内部 for 循环的元素作为输入参数传递给append()
方法。
执行 for 循环后,我们将获得一个从列表列表创建的平面列表,如下面的代码所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = []
for inner_list in myList:
for element in inner_list:
outputList.append(element)
print("The flattened list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The flattened list is:
[1, 2, 3, 4, 5, 12, 13, 23, 10, 20, 30, 11, 22, 33, 12, 24, 36]
除了使用 for 循环,您还可以使用 list comprehension 来展平列表列表,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = [x for l in myList for x in l]
print("The flattened list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The flattened list is:
[1, 2, 3, 4, 5, 12, 13, 23, 10, 20, 30, 11, 22, 33, 12, 24, 36]
Python 中列表的反向列表
我们可以用两种方法来反转列表的列表。一种方法是只颠倒内部列表的顺序,而保持内部列表中元素的顺序不变。另一种方法是颠倒内部列表中元素的顺序。
在 Python 中颠倒列表列表中内部列表的顺序
为了简化内部列表的逆序,我们将首先创建一个空列表,比如说outputList
。之后,我们将按照相反的顺序遍历列表。在遍历时,我们将把内部列表追加到outputList
。这样,在 for 循环执行之后,我们将得到列表outputList
的反向列表。您可以在下面的示例中观察到这一点。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = []
listlen = len(myList)
for i in range(listlen):
outputList.append(myList[listlen - 1 - i])
print("The reversed list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The reversed list is:
[[12, 24, 36], [11, 22, 33], [10, 20, 30], [12, 13, 23], [1, 2, 3, 4, 5]]
不使用 for 循环,可以使用reverse()
方法来反转列表的列表。在列表中调用reverse()
方法时,会颠倒列表中元素的顺序。当我们在列表列表上调用reverse()
方法时,它将反转内部列表的顺序,如下例所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.reverse()
print("The reversed list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The reversed list is:
[[12, 24, 36], [11, 22, 33], [10, 20, 30], [12, 13, 23], [1, 2, 3, 4, 5]]
在上面的方法中,原始列表被修改。然而,在前一个例子中情况并非如此。因此,您可以根据是否必须修改原始列表来选择一种方法。
在 Python 中颠倒列表列表中内部列表元素的顺序
除了颠倒内部列表的顺序之外,还可以颠倒内部列表中元素的顺序。为此,我们将首先创建一个空列表,比如说outputList
。之后,我们将使用 for 循环以逆序遍历列表列表。在 for 循环中,我们将创建一个空列表,比如说tempList
。之后,我们将使用另一个 for 循环以相反的顺序遍历内部列表的元素。在遍历内部列表的元素时,我们会将元素追加到tempList
中。在内部循环之外,我们将把tempList
附加到outputList
上。
执行 for 循环后,我们将得到一个列表,其中所有元素的顺序都相反,如下面的代码所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = []
listlen = len(myList)
for i in range(listlen):
tempList = []
currList = myList[listlen - 1 - i]
innerLen = len(currList)
for j in range(innerLen):
tempList.append(currList[innerLen - 1 - j])
outputList.append(tempList)
print("The reversed list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The reversed list is:
[[36, 24, 12], [33, 22, 11], [30, 20, 10], [23, 13, 12], [5, 4, 3, 2, 1]]
您可以使用如下所示的reverse()
方法,而不是使用 for 循环来反转内部列表的元素。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = []
listlen = len(myList)
for i in range(listlen):
myList[listlen - 1 - i].reverse()
outputList.append(myList[listlen - 1 - i])
print("The reversed list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The reversed list is:
[[36, 24, 12], [33, 22, 11], [30, 20, 10], [23, 13, 12], [5, 4, 3, 2, 1]]
这里,我们首先反转了 for 循环中的内部列表。之后,我们将其追加到了outputList
。通过这种方式,我们获得了列表的列表,其中内部列表以及内部列表的元素以与原始列表相反的顺序出现。
Python 中列表的排序列表
为了在 python 中对列表进行排序,我们可以使用 sort()方法或 sorted 函数。
使用 Sort()方法对 Python 中的列表进行排序
当在列表上调用sort()
方法时,该方法按照升序对列表的元素进行排序。当我们在列表列表上调用sort()
方法时,它根据内部列表的第一个元素对内部列表进行排序。
换句话说,在所有内部列表的第一个元素中,第一个元素最小的内部列表被分配列表列表中的第一个位置。类似地,在所有内部列表的第一个元素中,第一个元素最大的内部列表被分配到最后一个位置。
同样,如果两个内部列表在第一个位置有相同的元素,它们的位置根据第二个元素决定。如果内部列表的第二个元素也是相同的,列表的位置将根据第三个元素决定,依此类推。您可以在下面的示例中观察到这一点。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.sort()
print("The sorted list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [10, 20, 30], [11, 22, 33], [12, 13, 23], [12, 24, 36]]
您还可以更改sort()
方法的行为。为此,您可以使用sort()
方法的参数key
。'key
'方法将一个操作符或一个函数作为输入参数。例如,如果要根据内部列表的第三个元素对列表进行排序,可以传递一个使用内部列表第三个元素的运算符,如下所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.sort(key=lambda x: x[2])
print("The sorted list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
如果你想根据内部列表的最后一个元素对列表进行排序,你可以这样做。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.sort(key=lambda x: x[-1])
print("The sorted list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
类似地,如果您想根据内部列表的长度对列表进行排序,您可以将len()
函数传递给sort()
方法的参数“key
”。执行后,sort()
方法将使用内部列表的长度对列表进行排序。您可以在下面的示例中观察到这一点。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
myList.sort(key=len)
print("The sorted list is:")
print(myList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36], [1, 2, 3, 4, 5]]
使用 sorted()函数对 Python 中的列表进行排序
如果不允许修改列表的原始列表,可以使用 sorted()
功能对列表进行排序。sorted()
函数的工作方式类似于sort()
方法。但是,它不是对原始列表进行排序,而是返回一个排序后的列表。
要对列表进行排序,可以将列表传递给sorted()
函数。执行后,sorted()
函数将返回排序后的列表,如下例所示。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = sorted(myList)
print("The sorted list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [10, 20, 30], [11, 22, 33], [12, 13, 23], [12, 24, 36]]
您还可以使用key
参数来对使用sorted()
函数的列表进行排序。例如,您可以使用如下所示的sorted()
函数根据内部列表的第三个元素对列表进行排序。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = sorted(myList, key=lambda x: x[2])
print("The sorted list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
如果你想根据内部列表的最后一个元素对列表进行排序,你可以这样做。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = sorted(myList, key=lambda x: x[-1])
print("The sorted list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
类似地,如果您想根据内部列表的长度对列表进行排序,您可以将len()
函数传递给sorted()
函数的参数“key
”。执行后,sorted()
函数将使用内部列表的长度返回列表的排序列表。您可以在下面的示例中观察到这一点。
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = sorted(myList, key=len)
print("The sorted list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The sorted list is:
[[12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36], [1, 2, 3, 4, 5]]
在 Python 中连接两个列表
如果给了你两个列表,你想连接这两个列表,你可以使用+操作符,如下所示。
list1 = [[1, 2, 3, 4, 5], [12, 13, 23]]
list2 = [[10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The first list is:")
print(list1)
print("The second list is:")
print(list2)
print("The concatenated list is:")
myList = list1 + list2
print(myList)
输出:
The first list is:
[[1, 2, 3, 4, 5], [12, 13, 23]]
The second list is:
[[10, 20, 30], [11, 22, 33], [12, 24, 36]]
The concatenated list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
这里,两个列表的内部元素被连接成一个列表。
在 Python 中复制列表列表
要在 python 中复制列表的列表,我们可以使用copy
模块中提供的copy()
和deepcopy()
方法。
Python 中列表的浅拷贝列表
copy()
方法将嵌套列表作为输入参数。执行后,它返回一个类似于原始列表的列表列表。您可以在下面的示例中观察到这一点。
import copy
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = copy.copy(myList)
print("The copied list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The copied list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
上例中讨论的操作称为浅层复制。这里,复制列表和原始列表中的内部元素指向同一个内存位置。因此,每当我们在复制的列表中进行更改时,它都会反映在原始列表中。同样,如果我们在原始列表中做了更改,它会反映在复制的列表中。为了避免这种情况,可以使用deepcopy()
方法。
Python 中列表的深层拷贝列表
deepcopy()
方法将一个嵌套列表作为它的输入参数。执行后,它在不同的位置创建嵌套列表所有元素的副本,然后返回复制的列表。因此,每当我们在复制的列表中进行更改时,它不会反映在原始列表中。同样,如果我们在原始列表中做了更改,它不会反映在复制的列表中。您可以在下面的示例中观察到这一点。
import copy
myList = [[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
print("The original list is:")
print(myList)
outputList = copy.deepcopy(myList)
print("The copied list is:")
print(outputList)
输出:
The original list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
The copied list is:
[[1, 2, 3, 4, 5], [12, 13, 23], [10, 20, 30], [11, 22, 33], [12, 24, 36]]
结论
在本文中,我们讨论了 python 中的 list 列表。我们已经讨论了如何对列表的列表执行各种操作。我们还讨论了浅拷贝和深拷贝如何处理列表列表。此外,我们已经讨论了如何在 python 中对列表进行排序、反转、展平和遍历,要了解更多关于 python 编程语言的知识,您可以阅读这篇关于 python 中的字典理解的文章。您可能也会喜欢这篇关于 python 中的文件处理的文章。
Python API 列表
原文:https://www.pythonforbeginners.com/api/list-of-python-apis
Python API 的
许多互联网公司,如脸书、谷歌和 Twitter,都提供了应用程序编程接口(或 API ),您可以用它来构建自己的应用程序。API 是一组用于访问基于 web 的软件应用程序的编程指令和标准。包装器是一个 API 客户端,通常用于通过调用 API 本身将 API 包装成易于使用的函数。该页面为您提供了 python API 的列表,还提供了其 python 包装器的链接。
亚马逊网络服务是一系列远程计算服务的集合,共同构成了一个云计算平台,由 Amazon.com 通过互联网提供
Bing 是一个搜索引擎,它将最好的搜索和你的社交网络中的人聚集在一起,帮助你花更少的时间搜索,花更多的时间做事情。
URL 缩短和书签服务
博客发布服务
面向企业的在线文件共享和云内容管理服务。
使用 Delicious,世界领先的社会化书签服务,保存、分享和发现网络精华。
-
DropboxDisqus”
-
Disqus API bindings for Python
免费服务,让您将照片、文档和视频带到任何地方,并轻松共享
脸书是一个在线社交网络服务。
Foursquare 是一个基于位置的社交网站,面向智能手机等移动设备
- Api 文档
- 用于 Foursquare 的 Python 包装器
在线拍卖和购物网站
图像托管和视频托管网站
Python 的地理编码工具箱。官方 git 回购。
谷歌地图是谷歌提供的网络地图服务应用和技术
简单图像共享者
求职搜索引擎
在线照片共享、视频共享和社交网络服务,使用户能够拍摄照片和视频
世界上最大的在线音乐目录,由您的 scrobbles 提供支持。
世界上最大的专业网络
基于云的日志管理服务
点播互联网流媒体
IT 警报监控
基于云的日志管理服务
Pinterest 是一个图钉板风格的照片共享网站,允许用户创建和管理基于主题的图片集,如事件、兴趣和爱好。
一个社交新闻和娱乐网站,注册用户可以通过链接或文本帖子的形式提交内容
电影评论聚合器
分享您的声音
商业音乐流媒体服务
- API 文档
- pyspotify 为 spotify 的在线音乐流媒体服务提供了 Python 接口。
Technorati 是一个搜索博客的互联网搜索引擎。
Twitter 是一种在线社交网络服务和微博服务,它使用户能够发送和阅读多达 140 个字符的文本消息,即所谓的推文
- API 文档
- 围绕 Twitter API 的 Python 包装器
tumblr,其标志风格化为 Tumblr。,是一个微博平台和社交网站
维基百科是一个免费的、基于网络的、协作的、多语言的百科全书项目,由非营利的维基媒体基金会支持。
雅虎
门户网站,搜索引擎雅虎!搜索和相关服务,包括雅虎!目录,雅虎!邮件,雅虎!
- API 文档
- Yahoo!的 python 包装器。天气。
本地搜索网站
YouTube 是一个视频分享网站
是一个专注于计算机科学和创业的社交新闻网站。
地下世界
相关职位
相关
推荐 Python 培训
课程:Python 3 初学者
超过 15 小时的视频内容,为初学者提供指导。学习如何创建真实世界的应用程序并掌握基础知识。
Python 中的字符串列表到整数列表
原文:https://www.pythonforbeginners.com/basics/list-of-strings-to-list-of-integers-in-python
列表是 python 编程中最常用的容器对象之一。在本文中,我们将讨论在 python 中将字符串列表转换为整数列表的各种方法。
使用 For 循环将字符串列表转换为整数列表
我们可以使用 for 循环和int()
函数将字符串列表转换成整数列表。为此,我们将首先创建一个名为output_list
的空列表。之后,我们将使用 for 循环遍历字符串列表。在遍历时,我们将使用int()
函数将每个字符串元素转换成一个整数。之后,我们将使用append()
方法将该整数添加到output_list
中。在列表上调用append()
方法时,它接受一个元素作为输入参数,并将该元素追加到列表中。
在执行 for 循环后,我们将得到一个整数列表,如output_list
。您可以在下面的示例中观察到这一点。
myList = ["1", "2", "3", "4", "5"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
如果列表中有不能转换成整数的元素,程序将运行到如下所示的ValueError
异常。
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = []
for element in myList:
value = int(element)
output_list.append(value)
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
value = int(element)
ValueError: invalid literal for int() with base 10: 'PFB'
在这里,您可以看到字符串“PFB”无法转换为整数。因此,程序引发了ValueError
异常。
要处理该错误,可以在 python 中使用 try-except 块来进行异常处理。在 for 循环中,我们将使用 try 块中的int()
函数将元素转换为整数,然后将其追加到output_list
中。在 except 块中,我们将打印每个不能转换为整数的元素。这样,我们将只使用输入列表中那些可以使用 int()
函数直接转换成整数的元素来获得一个整数列表。
您可以在下面的示例中观察到这一点。
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = []
for element in myList:
try:
value = int(element)
output_list.append(value)
except ValueError:
print("{} cannot be converted to integer.".format(element))
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
PFB cannot be converted to integer.
The input list is: ['1', '2', '3', '4', '5', 'PFB']
The output list is: [1, 2, 3, 4, 5]
使用列表理解将字符串列表转换为整数列表
代替 for 循环,我们可以使用列表理解和int()
函数将字符串列表转换为整数列表,如下所示。
myList = ["1", "2", "3", "4", "5"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
使用列表理解有一个限制,如果输入列表的任何元素没有被转换成整数,我们将不能处理错误,因为我们不能在列表理解语法中使用异常处理。
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = [int(element) for element in myList]
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <module>
output_list = [int(element) for element in myList]
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <listcomp>
output_list = [int(element) for element in myList]
ValueError: invalid literal for int() with base 10: 'PFB'
使用 map()函数将字符串列表转换为整数列表
map()
函数用于将一个函数应用于一个可迭代对象的所有元素。map()
函数将一个函数作为第一个输入参数,将一个 iterable 对象作为第二个输入参数。它对输入 iterable 对象的所有元素逐一执行输入参数中给定的函数,并返回一个包含输出值的 iterable 对象。
为了将字符串列表转换成整数列表,我们将把 int()
函数作为第一个输入参数传递给map()
函数,并将字符串列表作为第二个输入参数。执行后,我们将得到如下所示的整数列表。
myList = ["1", "2", "3", "4", "5"]
output_list = list(map(int, myList))
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
The input list is: ['1', '2', '3', '4', '5']
The output list is: [1, 2, 3, 4, 5]
如果我们使用这种方法,如果输入列表包含不能转换为整数的字符串,我们将无法避免或处理异常。
myList = ["1", "2", "3", "4", "5", "PFB"]
output_list = list(map(int, myList))
print("The input list is:", myList)
print("The output list is:", output_list)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in <module>
output_list = list(map(int, myList))
ValueError: invalid literal for int() with base 10: 'PFB'
结论
在本文中,我们讨论了在 python 中将字符串列表转换为整数列表的三种方法。要了解更多关于字符串的知识,可以阅读这篇关于 python 中字符串格式化的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
Python 中的内置列表方法
列出内置方法
数据类型“List”有几个内置方法。
s = ['h','e','l','l','o'] #create a list
s.append('d') #append to end of list
len(s) #number of items in list
s.pop(2) #delete an item in the middle
s.sort() #sorting the list
s.reverse() #reversing the list
s.extend(['w','o']) #grow list
s.insert(1,2) #insert into list
s.remove('d') #remove first item in list with value e
s.pop() #remove last item in the list
s.pop(1) #remove indexed value from list
s.count('o') #search list and return number of instances found
s = range(0,10) #create a list over range
s = range(0,10,2) #create a list over range with start index and increment
用 Python 写的魔术 8 球
原文:https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python
概观
魔术 8 球是一种用于算命或寻求建议的玩具。
用 Python 写的魔术 8 球
在这个脚本中,我使用了 8 个可能的答案,但请随意添加更多。魔法 8 球里面有 20 个答案,你可以在这里找到全部
# Import the modules
import sys
import random
ans = True
while ans:
question = raw_input("Ask the magic 8 ball a question: (press enter to quit) ")
answers = random.randint(1,8)
if question == "":
sys.exit()
elif answers == 1:
print "It is certain"
elif answers == 2:
print "Outlook good"
elif answers == 3:
print "You may rely on it"
elif answers == 4:
print "Ask again later"
elif answers == 5:
print "Concentrate and ask again"
elif answers == 6:
print "Reply hazy, try again"
elif answers == 7:
print "My reply is no"
elif answers == 8:
print "My sources say no"
练习:有没有办法把所有的 elif 答案都换成别的?
使用 Virtualenvwrapper 让您的生活更轻松
原文:https://www.pythonforbeginners.com/basics/make-your-life-easier-virtualenvwrapper
当你进行大量的 Python 编程时,你可以用 Pip 把你的系统弄得一团糟。不同的 app 需要不同的需求。一个应用程序需要软件包的 1.2 版本,另一个需要 1.5 版本。然后…你就有麻烦了。
当您想知道 Pip 已经安装了哪些软件包时,请使用:
$ pip freeze
结果可能是一个很长的列表。
对于每个项目,无论是简单的应用程序还是巨大的 Django 项目,我都用 virtualenv 创建一个新的虚拟环境。一种简单的方法是使用 virtualenvwrapper。
Virtualenv 包装器入门
$ sudo pip install virtualenvwrapper
您可以在手册中找到一些高级设置。
安装完成后,让我们创建一个名为“testground”的新环境。
$ mkvirtualenv testground
如果您的 virtualenvwrapper 运行良好,您应该会看到如下内容:
New python executable in testground/bin/python
Installing Setuptools.........done.
Installing Pip..............done.
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/testground/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/testground/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/testground/bin/preactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/testground/bin/postactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/testground/bin/get_env_details
(testground)[[email protected]](/cdn-cgi/l/email-protection):~$
看一下最后一行,现在在提示符前显示(testground)。你的虚拟环境就在那里,你也在其中。
现在,执行一个 pip 冻结,它可能会导致如下结果:
$ pip freeze
argparse==1.2.1
wsgiref==0.1.2
该列表可以比环境之外的列表短得多。
您现在可以安装只影响这种环境的东西。我们试试枕头,2.2.2 版。
$ pip install Pillow==2.2.2
它现在将尝试安装枕头,完成后,做另一个 pip fip 冻结,并查看它是否已安装
在虚拟电视之间切换
让我们创建另一个环境:
$ mkvirtualenv coolapp
完成后,它应该会自动激活:
...................done.
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/coolapp/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/coolapp/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/coolapp/bin/preactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/coolapp/bin/postactivate
virtualenvwrapper.user_scripts creating /home/yourname/.virtualenvs/coolapp/bin/get_env_details
(coolapp)[[email protected]](/cdn-cgi/l/email-protection):~$
现在,让我们先来看看我们用“工作”这个神奇的词创造的虚拟世界:
$ workon testground
(testground)[[email protected]](/cdn-cgi/l/email-protection):~$
这就对了,就这么简单
没有站点包
与 vitualenv 一样,您可以告诉 virtualenvwapper 不要将系统 sitepackages 与–no-site-packages 一起使用:
$ mkvirtualenv anotherenv --no-site-packages
删除虚拟环境
使用 rmvirtualenv 可以很容易地删除虚拟 env:
$ rmvirtualenv coolapp
Removing coolapp...
列出所有虚拟人
$lsvirtualenv
列出你的站点包
$ lssitepackages
#can result in this:
easy_install.py Pillow-2.2.2-py2.7.egg-info pkg_resources.pyc
easy_install.pyc pip setuptools
_markerlib pip-1.4.1-py2.7.egg-info setuptools-0.9.8-py2.7.egg-info
PIL pkg_resources.py
在 Python 中合并数据帧
原文:https://www.pythonforbeginners.com/basics/merge-dataframes-in-python
Python 为我们提供了 pandas dataframes 来处理表格数据。在本文中,我们将讨论如何在 python 中合并两个数据帧。
Python 中如何合并两个数据帧?
假设我们有一个数据帧,其中包含一些学生的姓名、他们的学号以及他们选择学习的班级,如下所示。
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
此外,我们有一个数据帧,其中包含学生的编号和他们获得的分数,如下所示。
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
现在,我们必须合并给定的数据帧,使得结果数据帧包含每个学生的姓名、编号、年级、班级和相应的分数,如下所示。
Roll Marks Grade Class Name
0 11 85 A 1 Aditya
1 12 95 A 1 Chris
2 13 75 B 1 Sam
3 14 75 B 1 Joel
4 16 78 B 1 Samantha
5 15 55 C 1 Tom
6 20 72 B 1 Tina
7 24 92 A 1 Amy
为了获得输出,我们将使用 pandas 模块中定义的merge()
方法。merge()
方法的语法如下。
pd.merge(df1,df2, on)
在这里,
df1
表示第一个数据帧。- 参数
df2
表示将被合并的第二数据帧。 - 参数
‘on’
是数据帧的列名,用于比较给定数据帧的列。如果两个数据帧中的行在对应于“on”参数的列中具有相同的值,则将它们合并在一起。
merge()
方法还接受其他几个参数。你可以在这个文档里看看。
为了合并给定的数据帧,我们将调用merge()
方法,首先将数据帧作为第一个输入参数。随后,我们将把包含标记的数据帧作为第二个输入参数传递给merge()
方法。对于 ‘on’
参数,我们将传递‘Roll’
列名。这样,来自给定数据帧的对应于相同卷号的行将被合并,并且将产生如下所示的结果数据帧。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_on="Roll", right_on="Roll")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85 A 1 Aditya
1 12 95 A 1 Chris
2 13 75 B 1 Sam
3 14 75 B 1 Joel
4 16 78 B 1 Samantha
5 15 55 C 1 Tom
6 20 72 B 1 Tina
7 24 92 A 1 Amy
如果第二个数据帧中的行与第一个数据帧中的任何行都不对应,则从结果中忽略这些行。类似地,如果第一个数据帧包含与第二个数据帧不对应的行,则这些行将从结果中省略。你可以在上面的例子中观察到这一点。
在 Python 中使用外部连接合并数据帧
为了包含省略的行,我们可以在merge()
方法中使用参数‘how’
。‘how’
参数有默认值‘inner’
。因此,只有那些同时出现在两个输入数据帧中的行才会包含在结果数据帧中。要包含省略的数据帧,您可以将值‘outer’
传递给参数‘how’
,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="outer",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85.0 A 1.0 Aditya
1 12 95.0 A 1.0 Chris
2 13 75.0 B 1.0 Sam
3 14 75.0 B 1.0 Joel
4 16 78.0 B 1.0 Samantha
5 15 55.0 C 1.0 Tom
6 19 75.0 B NaN NaN
7 20 72.0 B 1.0 Tina
8 24 92.0 A 1.0 Amy
9 25 95.0 A NaN NaN
10 17 NaN NaN 1.0 Pablo
11 30 NaN NaN 1.0 Justin
12 31 NaN NaN 1.0 Karl
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
在 Python 中使用左右连接合并数据帧
如果您想只包含第一个数据帧中省略的行,可以将值‘left’
传递给参数‘how’
。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="left",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85 A 1.0 Aditya
1 12 95 A 1.0 Chris
2 13 75 B 1.0 Sam
3 14 75 B 1.0 Joel
4 16 78 B 1.0 Samantha
5 15 55 C 1.0 Tom
6 19 75 B NaN NaN
7 20 72 B 1.0 Tina
8 24 92 A 1.0 Amy
9 25 95 A NaN NaN
类似地,如果您想只包含第二个数据帧中省略的行,您可以将值‘right’
传递给参数‘how’
,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="right",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85.0 A 1 Aditya
1 12 95.0 A 1 Chris
2 13 75.0 B 1 Sam
3 14 75.0 B 1 Joel
4 15 55.0 C 1 Tom
5 16 78.0 B 1 Samantha
6 17 NaN NaN 1 Pablo
7 20 72.0 B 1 Tina
8 24 92.0 A 1 Amy
9 30 NaN NaN 1 Justin
10 31 NaN NaN 1 Karl
结论
在本文中,我们讨论了如何使用merge()
方法在 python 中合并两个数据帧。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
在 Python 中合并字典
原文:https://www.pythonforbeginners.com/dictionary/merge-dictionaries-in-python
在编程时,可能会出现需要在 python 中合并两个或更多字典的情况。在本文中,我们将研究如何使用不同的方法在 python 中合并两个或更多的字典。
使用 items()方法合并字典。
我们可以使用 items()方法通过将一个字典的条目逐个添加到另一个字典来合并两个字典。在字典上调用 items()方法时,会返回包含键值对的元组列表。如果我们必须合并两个字典,我们将一个字典的条目一个接一个地添加到另一个字典中,如下所示。
dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
for key,value in dict2.items():
dict1[key]=value
print("Merged dictionary is:")
print(dict1)
输出:
First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
在使用上述方法时,我们必须考虑这样一点:如果两个字典之间有公共键,那么最终的字典将具有公共键,这些公共键的值来自我们从中提取条目的第二个字典。此外,只有添加条目的第一个字典会被修改,而第二个字典不会发生任何变化。
使用 popitem()方法合并词典。
popitem()方法用于从 python 字典中删除一个条目。在字典上调用时,popitem()方法删除字典中最近添加的项,并以元组的形式作为键值对返回该项。
为了合并字典,我们将使用 popitem()方法从一个字典中弹出条目,并不断将其添加到另一个字典中。
dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
while dict2:
key,value=dict2.popitem()
dict1[key]=value
print("Merged dictionary is:")
print(dict1)
输出:
First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 6: 36, 5: 25, 4: 16}
当使用上述方法时,我们必须记住,要合并的两个字典都被修改。从中删除条目的第二个字典变空,而添加条目的第一个字典也被修改。同样,我们必须考虑这一点,如果在被合并的字典之间有公共键,合并的字典将包含来自第二个字典的值,公共键的项从该字典中弹出。
使用 keys()方法。
我们还可以使用 keys()方法在 python 中合并两个字典。在字典上调用 keys()方法时,会返回字典中的键列表。我们将使用 keys()方法从字典中获取所有的键,然后我们可以访问这些键的相关值。之后,我们可以将键值对添加到另一个字典中,如下所示。
dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
keylist=dict2.keys()
for key in keylist:
dict1[key]=dict2[key]
print("Merged dictionary is:")
print(dict1)
输出:
First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
当我们在 python 中使用上述方法合并两个字典时,我们必须记住,我们从中获取键的第二个字典不会被修改。只有添加了键和值的字典才会被修改。此外,如果被合并的两个字典具有共同的关键字,那么合并的字典将具有来自从中获得关键字的字典的共同关键字的值。
使用 update()方法合并字典
我们可以使用 update()方法直接将一个字典合并到另一个字典。在一个字典上调用 update()方法,它将另一个字典作为输入参数。我们可以使用 update()方法合并字典,如下所示。
dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
dict1.update(dict2)
print("Merged dictionary is:")
print(dict1)
输出:
First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
在这种情况下,当我们使用 python 中的 update()方法合并两个字典时,公共键被赋予字典中作为参数传递的值。同样,作为参数传递的第二个字典不会被修改,而调用 update()方法的第一个字典会被修改并转换为最终字典。
使用**运算符合并词典
双星号()运算符用于将可变长度的关键字参数传递给函数。我们还可以使用运算符来合并两个字典。当我们对字典应用**操作符时,它反序列化字典并将其转换为键值对的集合,然后使用键值对形成新的字典。
dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
mergedDict={**dict1,**dict2}
print("Merged dictionary is:")
print(mergedDict)
输出:
First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
我们可以使用**运算符一次合并任意数量的字典。此外,不得不合并的原始字典都不会被修改。它们保持原样。在该方法中,当要合并的字典具有公共关键字时,各个关键字的值将从合并时序列中最后出现的字典中取得。
结论
在本文中,我们看到了如何使用不同的方法在 python 中合并字典。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
Python 中的合并列表
原文:https://www.pythonforbeginners.com/lists/merge-lists-in-python
在编程时,我们可能需要在 python 中合并两个或多个列表。在本文中,我们将看看在 python 中合并两个列表的不同方法。
使用 python 中的 append()方法合并列表
我们可以使用 append()方法将一个列表合并到另一个列表中。append()方法用于向现有列表添加新元素。要使用 append()方法合并两个列表,我们将获取一个列表,并使用 for 循环将另一个列表中的元素逐个添加到该列表中。这可以如下进行。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
for i in list2:
list1.append(i)
print("Merged list is:")
print(list1)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
在使用 append()方法合并列表的过程中,随着第二个输入列表中的元素被添加到第一个输入列表中,第一个输入列表被修改。而对第二个列表没有影响,我们从第二个列表中取出元素添加到第一个列表中。
使用 append()和 pop()方法
除了 append()方法,我们还可以使用 pop()方法在 python 中合并两个列表。对任何列表调用 pop()方法时,都会删除最后一个元素并返回它。我们将使用 pop()方法从一个列表中取出元素,并使用 append()方法向另一个列表中添加元素。这可以如下进行。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
while list2:
temp=list2.pop()
list1.append(temp)
print("Merged list is:")
print(list1)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 8, 7, 6, 5]
当使用上述方法合并两个列表时,两个输入列表都会被修改。当其他列表中的元素被添加到第一个列表中时,第一个输入列表被修改。使用 pop()方法删除第二个列表中的所有元素,因此在合并列表后,第二个列表变为空。在输出中,我们还可以看到第二个列表中的元素在合并列表中以相反的顺序出现。
使用列表理解
我们还可以使用列表理解来合并 python 中的两个或更多列表。为此,我们将首先创建一个要合并的所有列表的列表,然后我们可以使用列表理解来创建合并的列表,如下所示。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
combined_list=[list1,list2]
merged_list=[item for sublist in combined_list for item in sublist]
print("Merged list is:")
print(merged_list)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
当我们使用列表理解合并列表时,没有一个要被合并的输入列表会被修改。
在 python 中使用+运算符合并列表
我们可以使用+运算符直接合并两个或多个列表,只需使用+运算符将所有列表相加即可,如下所示。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
merged_list=list1+list2
print("Merged list is:")
print(merged_list)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
当我们使用上面程序中的+操作符合并两个列表时,被合并的输入列表都不会被修改。
使用星号运算符
我们可以使用打包操作符*将两个或多个列表打包在一起,以合并列表,如下所示。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
merged_list=[*list1,*list2]
print("Merged list is:")
print(merged_list)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
当我们使用星号操作符合并两个列表时,被合并的输入列表都不会被修改。这种方法对于一次合并三个或更多列表也很方便,因为我们可以通过使用*操作符简单地提到每个列表,在输出的合并列表中包含每个列表的元素。
使用 extend()方法
要使用 extend()方法合并两个或多个列表,我们可以通过添加其他列表的元素来执行第一个列表的就地扩展,如下所示。
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
list1.extend(list2)
print("Merged list is:")
print(list1)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
当我们使用 extend()方法合并两个列表时,extend()方法所在的列表会随着其他列表中的元素被添加到其中而被修改。其他列表不受该操作的影响。
使用 python 中的 itertools.chain()方法合并列表
我们还可以使用 itertools.chain()方法在 python 中合并两个或多个列表。为此,我们将列表作为参数传递给 itertools.chain()方法,该方法返回一个 iterable,其中包含要合并的列表的所有元素,这些元素可以进一步转换为一个列表。
import itertools
list1=[1,2,3,4]
list2=[5,6,7,8]
print("First list is:")
print(list1)
print("Second list is:")
print(list2)
merged_list=list(itertools.chain(list1,list2))
print("Merged list is:")
print(merged_list)
输出:
First list is:
[1, 2, 3, 4]
Second list is:
[5, 6, 7, 8]
Merged list is:
[1, 2, 3, 4, 5, 6, 7, 8]
当我们使用 itertools.chain()方法合并列表时,没有一个输入列表被修改。这种在 python 中合并列表的方式可以方便地合并两个以上的列表,因为我们只需将输入列表作为参数传递给 itertools.chain()方法。
结论
在本文中,我们看到了使用不同的方法和模块在 python 中合并两个或多个列表的各种方法。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
命令行参数(sys.argv)
原文:https://www.pythonforbeginners.com/argv/more-fun-with-sys-argv
Python 中的 sys 模块是许多可用的库代码模块之一。
sys.argv 是什么?
sys.argv 是传递给 Python 程序的命令行参数列表。
argv 表示通过命令行输入的所有项目,它基本上是一个数组,保存我们程序的命令行参数。
不要忘记计数是从零(0)而不是一(1)开始的。
我如何使用它?
要使用它,您必须首先导入它(导入系统)
第一个参数 sys.argv[0]始终是程序被调用时的名称,
,sys.argv[1]是传递给程序的第一个参数。
通常,您会对列表进行切片以访问实际的命令行参数:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
这是一个如何从命令行读取参数的例子
import sys
for x in sys.argv:
print "Argument: ", x
len(sys.argv) , checks how many arguments that have been entered.
len(sys.argv) != 2 just checks whether you entered at least two elements
import sys
if len (sys.argv) != 2 :
print "Usage: python ex.py "
sys.exit (1)
要运行它,只需输入:
>python ex.py
Argument: ex.py
>python ex.py hello
Argument: ex.py
Argument: hello
>python ex.py hello world
Argument: ex.py
Argument: hello
Argument: world
2021 年最常见的 Python 面试问题
原文:https://www.pythonforbeginners.com/basics/most-common-python-interview-questions
Python 是当今市场上最受欢迎的技能之一。
通过掌握 Python 编程语言,你也可以加入编程大师和奇才的行列,雇主们希望在专注于数据科学、机器学习、商业智能等领域或本质上是科学和数字的公司中填补职位。要被录用,你你应该精通 Python 和 Python 面试问题。
了解 Python 编程的所有知识,包括如何从多个类继承到切片,以及如何轻松使用所有数据结构,包括数组、字符串、列表、元组和矩阵。
为了你自己和你的职业生涯,你能做的最好的事情就是好好学习,准备回答一些棘手的 Python 面试问题。
做好准备将有助于缓解紧张,减少技术性面试的威胁。为了帮助你提前准备技术面试,我们整理了 2020 年最常见的 Python 面试问题。
通过让你的朋友问你这些问题来和你的朋友练习。如果可能的话,用你的智能手机拍摄模拟面试,检查你的答案和你回答问题的方式。
Q1:告诉我 Python 的主要特点是什么?
A1: 以下是 Python 的一些关键特性。 Python 面试技巧:选择至少 5 个,自信地讲述 Python 为什么伟大。
| 解释的 vs 编译的(如 C) | Python 是一种解释型语言,这意味着代码在使用前不必编译。 |
| 动态键入 | 不需要声明变量的数据类型。Python 通过存储在其中的值自动识别数据类型。 |
| OOP | Python 遵循面向对象的范式,这意味着您拥有封装、继承、多态等能力。 |
| 跨平台 | 一旦编写完成,Python 可以移植到另一个平台上,几乎不需要修改。 |
| 通用目的 | Python 是一种通用语言,这意味着它可以用于任何领域,包括数据科学、机器学习、自动化、学习、科学、数学等。 |
| 函数和类是一级对象 | Python 函数和类可以赋给变量,并作为参数传递给其他函数。 |
| 扩展库 | Python 提供了丰富的库列表,用强大的函数和方法来扩展语言。 |
PYTHONPATH 环境变量的目的是什么?
A2: Python 使用环境变量来设置 Python 将要运行的环境。PYTHONPATH 用于包含 Python 的模块和包所在的路径或目录。请注意,PYTHONPATH 变量通常是在安装 Python 时设置的。
Q3:python startup、PYTHONCASEOK、PYTHONHOME 环境变量是什么?
A3: PYTHONSTARTUP 是您为 Python 文件设置的路径,该文件将在启动 Python 解释器模式(即口译员)。它用于初始化设置,如颜色、预加载常用模块等。
PYTHONCASEOK 用于在不区分大小写的文件系统中查找模块文件。
PYTHONHOME 是一个替代的模块搜索路径。
Q4 :列表和元组有什么区别?
A4: 列表和元组的主要区别在于,列表是可变的,元组是不可变的。不能添加元组或更改维度,而列表可以。一个很好的例子是在数学意义上用作轴的(x,y,z)元组。改变这种状况是有意义的。
Q5 :解释 Python 中的继承?还有 Python 支持多重继承吗?
继承是指一个(子)类继承了另一个类的某些特征。父类或类继承的类将定义基类变量和方法供子类使用。
与 Java 不同,Python 支持多重继承。
Q6:Python 中的字典是什么,如何创建字典?
A6:Python 字典是一种用键值对实现的数据结构。字典在其他语言中被称为关联数组,它将一个值与一个键相关联。要在 Python 中创建字典,花括号用于定义字典,如下所示:
Sampledict = {"make ":起亚,"车型":魂,"发动机尺寸":" 1.6L"}
Q7 :负指标有什么用?
A7 :负指数让你从右边数,而不是从左边数。换句话说,你可以从末尾到开始索引一个字符串或者一个列表。
Q8:range 和 xrange 有什么区别?
A8 :两个函数都生成一个整数列表供您使用,但不同的是 range()函数返回一个 Python list 对象,而 xrange()返回一个 xrange 对象。
Q9 :什么模块有 split()、sub()和 subn()方法?这些方法是做什么的?
A9 :这些函数来自正则表达式 (re)模块,用于修改字符串表达式。
| 拆分() | 该函数根据字符或模式的出现次数分割字符串。当 Python 找到字符或模式时,它将字符串中剩余的字符作为结果列表的一部分返回。参见如何在 Python 中使用 Split |
| sub() | 这个函数在一个字符串中搜索一个模式,当找到时,用一个替换字符串替换子字符串。 |
| subn() | 这个函数与 sub()类似,但是它的输出不同,因为它返回一个元组,其中包含所有替换和新字符串的总数。 |
Q10:Python 中酸洗和拆洗是什么意思?你什么时候会用它?
A10:pickle 模块用于序列化(或 pickle)或反序列化(unpickle)Python 对象结构。pickling 和 unpickling 的一个用途是当您想要将 Python 对象存储到数据库中时。为此,您必须在将对象保存到数据库之前将其转换为字节流。
Q11:map()函数是用来做什么的?
A11:map()函数有两个参数,一个函数和一个可迭代列表。该函数应用于 iterable 列表中的每个元素。
Q12 :什么是‘with’语句,你会在什么时候使用它?
A12:‘with’语句是一个复合语句,用于异常处理。它简化了文件流等资源的管理。
Q13:Python 需要缩进吗,还是为了让代码更容易阅读?
A13 :在其他语言中,缩进是为了让代码更易读,但是在 Python 中,缩进表示代码块。
Q14 :你会在哪个模块中找到 random()函数?
A14 :可以在 NumPy 中找到生成随机数的函数 random()。
Q15:NumPy 是什么?
NumPy 是科学计算的基础包。它是一个包含多维数组(或矩阵数据结构)的开源库。
Q16 :解释 Python 中的局部和全局变量。
A16 :局部变量只能在一个块中访问,全局变量可以在整个代码中访问。为了声明一个全局变量,使用了 global 关键字。
你会用什么来存储一堆不同类型的数据?数组还是列表?
A17:Python 中的数组是最具限制性的数据结构,因为数组中存储的元素必须是相同的数据类型。答案是 list,因为只有 list 才能包含不同数据类型的元素。
Q18:Python 是怎样一种解释型语言?
A18: Python 代码在运行前不在机器级代码中。这使得 Python 成为一种解释型语言。
Q19 :什么是 Python 装饰器?
装饰器是任何用于修改函数或类的可调用对象。对函数或类的引用被传递给装饰器,装饰器返回修改后的函数或类。(有趣的是,Python 通常通过值传递参数,但是在 decorators 的情况下,函数或类是通过引用传递的)。
Q20:Python 的字符串是不可变的还是可变的?
A20: 在 Python 中,字符串是不可变的。不能修改 string 对象,但可以通过重新分配变量来创建新的 string 对象。
Q21 :什么是切片?
A21 :切片在 Python 中的意思是提供序列、字符串、列表或元组的‘切片’或片段。
Q22 :你用什么来捕捉和处理异常?
A22 :为了捕捉和处理异常,使用了 try 语句。
Q23:Python 中的 self 是什么?
A23:self 用于表示类的实例,以便访问属性和方法。
Q24 :你用什么函数给数组添加元素?
A24: 有三个函数:append(),insert()和 extend()。append()将元素添加到列表的末尾,insert()将元素添加到列表中,extend()将另一个列表添加到现有列表中。
Q25 :浅拷贝和深拷贝有什么区别?
A25 :浅拷贝复制地址,深拷贝复制地址和地址引用的数据。
Q26:Python 支持多重继承吗?
A26 :与 Java 不同,Python 支持多重继承。
Q27 :如何移除 Python 数组中的值?
A27 :有两个函数可以从数组中移除元素。它们是 pop()和 remove()。
Q28 :如果值不在列表中,那么 list.index(value)会返回什么?会是零还是别的?
A28: 如果 index()函数中指定的值没有在列表中找到,那么 Python 将返回 ValueError 异常
Q29 :什么是 init?
A29:_ init _ 是一个构造函数方法,用于在实例化一个对象时初始化一个类的属性。
Q30 :什么是 mylist[-1]如果 mylist = [2,244,56,95]?
A30 :答案是 95。
Q31 :什么是 lambda 函数?
A31 : Lambda 函数是匿名函数,没有名字,可以有任意多的参数。唯一的规定是 lambda 函数只有一个表达式。没有显式返回,因为当计算表达式时,值隐式返回。
Q32 :突破、继续、传球有什么区别?
A32 :当某些条件发生时,break、continue 和 pass 语句用在 FOR 和 WHILE 循环中。break 语句允许您在外部条件发生时退出循环。通常在 if 语句中使用 break 来测试循环中的条件。continue 语句允许您通过在 continue 语句之后不执行任何操作来跳过循环部分。pass 语句允许您继续循环的一部分,就像外部条件不满足一样。
Q33:[::-1]是做什么的?
A33 :反转一个列表。
Q34 :如何检查一个字符串是否为数字?
A34: 如果字符串中的所有字符都是数字,函数 isnumeric()返回 true。
Q35 :什么函数在换行符处分割一个字符串?
A35:split lines()函数将在换行符处分割字符串。
Q36 :如果 mylist = ['hello ',' world ',' in ',' Paris'],print mylist[0]的输出是什么?
A36 :答案是‘hello’,因为索引 0 代表第一个元素。
Q37 :如果 str = 'Hello ',打印 str * 2 的输出是什么?
A37: 乘数将一个字符串重复多次。所以答案是“HelloHello”
Q38: 如果 str = 'Hello World ',print str[2:5]的输出是什么?
A38: 答案是‘llo’。
Q39: 如何将字符转换成整数?
A39 :函数 ord()会把字符转换成整数。同时,学习额外的转换,比如将整数转换成八进制。
Q40 :列表和数组有什么区别?
在存储大量数据时,数组比 Python 中的列表更有效,但数组中的值必须都是同一类型。数组非常适合数值计算,而列表则不然。例如,可以用一行代码分割数组中的每个元素。对于列表,你需要几行代码来做同样的事情。
Q41 :模块无法加载时会引发什么异常?
A41 :当 import 语句加载模块失败时,引发 ImportError。
Q42 :提供代码用零初始化一个 5 乘 5 的 Numpy 数组?
A42 :答案如下:
将 numpy 作为 np 导入
n1 = np.zeros((5,5))
n1
Q43 :提供从字典创建数据帧的代码?
A43: 答案如下:
进口熊猫作为 pd
颜色= ["蓝色"、"绿色"、"白色"、"黑色"]
汽车= ["丰田"、"本田"、"起亚"、"宝马"]
d = { "汽车":汽车,"颜色":颜色}
f = pd。数据帧(d)
f
Q44 :链表上 append()和 extend()有什么区别?
A44:append()将一个元素添加到一个列表的末尾,而 extend()将另一个列表添加到一个列表中。
列表 1 = [1,2,3]
list1.append(4)
列表 1 = [1,2,3,4]
列表 2 = [5,6,7,8]
list1.extend(list2)
列表 1 = [1,2,3,4,5,6,7,8]
Q45:index()函数和 find()函数有什么区别?
两个函数都将在迭代器中搜索一个值。唯一的区别是,如果值不是迭代器的一部分,index()函数将中断并返回 ValueError 异常。如果没有找到值,find()函数将返回-1。
Q46: 当用户按下 Ctrl-C 或 Delete 键时会引发什么异常?
A46 :键盘中断异常产生。
Q47:Python 支持递归吗?如果是,你能深入多深?如果超过了会怎么样?
A47 :是的,Python 支持递归,最高级别 997。如果超过该值,将引发 RecursionError 异常。
Q48:Python 中内存是如何管理的?
所有的 Python 对象和数据结构都保存在一个程序员无法访问的私有堆中。每当一个对象需要内存时,Python 内存管理器就会在堆中分配空间。Python 有一个内置的垃圾收集器,可以回收私有堆中的空间用于更多的分配。
Q49:Python 中可以创建空类吗?如果有,如何实现?
使用 pass 语句可以创建一个空类,但是注意你仍然可以实例化这个类。
Q50: 如何用 Python 代码写注释?
A50 :注释以“#”为前缀。参见如何在 Python 中使用注释
总之,学习这些 python 面试问题会让你领先一步。花点时间检查一下答案,这样你就可以对每个答案给出你自己的、自信的解释。
Python 中的命名元组
原文:https://www.pythonforbeginners.com/data-types/namedtuple-in-python
你必须在你的程序中使用一个元组或者一个 python 字典。尽管它们是非常有用的数据结构,但是它们也有一些缺点。在这篇文章中,我们将学习什么是 python 中的命名元组,以及我们如何用它来代替元组或字典。
元组和字典的问题
假设您正在创建一个 python 应用程序,并且您必须指定图形界面的颜色。在这种情况下,您可以使用具有(红、绿、蓝)值的元组,如下所示。
color=(100,125,130)
但是,这里有一个问题。假设你的队友读了你的代码,他不明白上面例子中的元组意味着什么。可能是(红、绿、蓝)值,也可能是(色调、饱和度、亮度)值,依他而定。为了避免这种混乱,你可以使用一本以红绿蓝为基调的字典。
color={"red":100, "green":125, "blue": 130}
同样,当我们使用字典时,我们必须为图形界面中使用的每个组件创建一个字典。这将使我们的代码变得多余和不可读。为了解决这些问题,我们可以在 python 程序中使用 namedtuple。让我们讨论它是什么以及我们将如何使用它。
python 中的命名元组是什么?
您可以将命名元组视为元组和字典之间的中间数据结构。顾名思义,python 中的 namedtuple 是带有命名字段的元组。通常,我们使用元组的索引来访问它们的元素。但是在 namedtuple 中,我们可以指定每个索引的名称,然后我们可以使用这些名称来访问元素。
让我们在下面的章节中详细讨论这一点。
如何在 Python 中创建 namedtuple?
集合模块中定义了 Namedtuple。您可以按如下方式导入它。
from collections import namedtuple
导入 namedtuple 模块后,可以使用 namedtuple()构造函数创建一个 namedtuple。
namedtuple()构造函数采用要创建的对象类的名称及其字段名称作为输入参数。然后它创建 tuple 的一个子类,其中的字段被命名。
例如,我们可以用字段名“红”、“绿”和“蓝”定义一个“颜色”名元组,如下所示。
Color = namedtuple("Color", ["red", "green", "blue"])
在定义了 namedtuple 子类之后,我们可以通过给定字段值来创建命名元组,如下所示。
color=Color(100,125,130)
我们还可以使用如下的属性符号来访问 namedtuple 的不同字段中的值。
from collections import namedtuple
Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)
print("The namedtuple is:", color)
print("The red value is:", color.red)
print("The green value is:", color.green)
print("The blue value is:", color.blue)
输出:
The namedtuple is: Color(red=100, green=125, blue=130)
The red value is: 100
The green value is: 125
The blue value is: 130
如果需要,您还可以找到 namedtuple 的字段名称。为此,您可以使用包含字段名称的 _fields 属性,如下所示。
from collections import namedtuple
Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)
print("The namedtuple is:", color)
print("The fields of the namedtuple are:", color._fields)
输出:
The namedtuple is: Color(red=100, green=125, blue=130)
The fields of the namedtuple are: ('red', 'green', 'blue')
在 Python 中使用命名元组的好处
与元组和字典相比,使用命名元组有几个好处。
- 与元组不同,命名元组允许索引和字段名。这使得我们的代码更容易理解。
- 与字典不同,命名元组是不可变的,可以存储在一个集合中。此外,使用 namedtuple 代替字典需要我们编写更少的代码。
- 尽管有这些优点,命名元组与元组相比使用几乎相似的内存。
如何修改命名元组?
namedtuple 是 tuple 的子类,被认为是不可变的。它可以存储在一个集合中,并显示不可变对象的每个属性。但是,我们可以修改命名元组中的值。为此,我们可以使用 _replace()方法,该方法采用带有字段名和新值的关键字参数。之后,它返回修改后的 namedtuple,如下所示。
from collections import namedtuple
Color = namedtuple("Color", ["red", "green", "blue"])
color = Color(100, 125, 130)
print("The original namedtuple is:", color)
color = color._replace(red=200)
print("The modified namedtuple is:", color)
输出:
The original namedtuple is: Color(red=100, green=125, blue=130)
The modified namedtuple is: Color(red=200, green=125, blue=130)
结论
在本文中,我们讨论了 python 中的 namedtuple。我们还讨论了它的使用以及相对于元组和字典的好处。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的嵌套列表理解
原文:https://www.pythonforbeginners.com/lists/nested-list-comprehensions-in-python
Python 吸引程序员的一个方法是鼓励优雅、易读的代码。它通过各种功能做到这一点,包括列表理解。
编写更高效的代码有助于程序员节省时间和精力。Python 中的列表理解通过简化在 Python 中执行复杂语句所需的语法来实现这一目标。
嵌套列表理解更进一步,允许 Python 在一行代码中创建一个列表列表。这是一个强大而灵活的特性,通常用于生成矩阵。
为什么使用列表理解?
列表理解是一个有吸引力的特性,因为它可以节省程序员的时间和精力。简化语法意味着编码人员可以用更少的代码完成复杂的操作。
因为列表理解语句被简化了,它们通常更容易阅读。
使用列表理解的优势包括:
- 通常更容易阅读和维护
- 需要编写更少的代码
- 强大而灵活的功能
- 性能优于循环
然而,在每一种情况下,使用列表理解并不会使事情变得更容易。这就是为什么我们要深入研究一些何时以及如何使用这个流行的 Python 特性的例子。
如何使用嵌套列表理解
Python 中的列表理解使用表示,使用关键字中的。这些关键字告诉 Python 我们想要在一个 iterable 上循环并对结果做一些事情。为了完成列表理解,我们需要一组方括号内的语句。
基本列表理解语法:
new_list = [expression for item in list]
表达式:该表达式用于修改报表中的各项。
项:可迭代
列表中的元素:可迭代对象。
嵌套列表理解语法:
new_list = [[expression for item in list] for item in list]
可重复的
使用 range() 函数生成 iterable 是 Python 中的一种常见技术。iterable 是一个可以迭代的 Python 对象,比如一个列表。
我们将使用 range()来构造 for 循环,我们可以用它来构建矩阵。
用 Python 构建矩阵
我们可以使用嵌套的方括号在 Python 中构建一个矩阵。在这个例子中,你可以看到我们正在创建一个列表列表。通过将三个不同的列表包装在另一个列表中,我们可以构建一个 Python 列表。
示例 1:一个基本的 Python 矩阵
# create a list of lists
matrix = [[0,1,2],[0,1,2],[0,1,2]]
print(matrix)
输出
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
或者,可以用一对嵌套的 for 循环和 append() 方法创建一个矩阵。
示例 2:使用 for 循环创建矩阵
matrix = []
for y in range(3):
matrix.append([])
for x in range(3):
matrix[y].append(x)
print(matrix)
输出
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
最后,我们将使用 Python 列表理解创建一个矩阵。list comprehension 语句使用嵌套括号、 range() 函数以及关键字表示和中的来构造语句。
matrix = [[x for x in range(3)] for y in range(3)]
print(matrix)
输出
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
如您所见,list comprehension 语句比构造矩阵的 double for 循环方法占用更少的空间。
在每个示例中,输出都是相同的。每种技术都可以用来创建相同的 Python 列表。
然而,使用嵌套列表方法,我们只需要一行代码就可以获得想要的结果。我们使用的方法就像嵌套循环一样灵活,这种方法读写起来很麻烦。
运用列表理解的例子
让我们用列表理解来创建一个井字游戏板。大多数人都熟悉井字游戏。但如果你一直生活在岩石下,这是一个简单的领土游戏。
一个基本的井字游戏棋盘是一个 3×3 的正方形网格。我们可以用列表理解来创建游戏板,在每个方格中填入一个空格。
示例 3:构建井字游戏棋盘
tic_tac_toe_board = [[' ' for x in range(3)] for y in range(3)]
def PrintMatrix(matrix):
for row in range(len(matrix)):
print(matrix[row])
PrintMatrix(tic_tac_toe_board)
输出
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
我们可以使用列表符号在游戏板上放置一个“X”。
tic_tac_toe_board[1][1] = 'X'
PrintMatrix(tic_tac_toe_board)
输出
[' ', ' ', ' ']
[' ', 'X', ' ']
[' ', ' ', ' ']
从序列创建矩阵
使用列表理解可以将一系列数字转化为矩阵。通过操作列表理解语句的表达式部分,生成的矩阵中的每一项都将被修改。
我们将让矩阵存储一系列数字 0-8,均匀地分成三行。
示例 4:使用表达式
matrix = [[x+(y*3) for x in range(3)] for y in range(3)]
print(matrix)
输出
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
转置嵌套列表
我们可以使用 Python 列表理解来转置一个矩阵。要转置一个矩阵,我们需要把每一行变成一列。
示例 5:转置矩阵
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
transposed = [[x[y] for x in matrix] for y in range(len(matrix))]
print(transposed)
输出
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
过滤嵌套列表理解语句
我们可以为列表理解提供一个条件,作为结果的过滤器。只有符合条件标准的项目才会被接受。
条件:选择满足条件标准的元素。
使用条件,我们可以告诉 Python 我们只对列表中的特定元素感兴趣。选择哪些元素将取决于所提供的条件。
例如,我们可以为列表理解提供一个只选择偶数的条件。
示例 6:过滤偶数矩阵
matrix = [x for x in range(1,10) if x%2 == 0]
print(matrix)
输出
[2, 4, 6, 8]]
此外,通过嵌套列表理解,我们可以创建一个偶数矩阵。
matrix = [[x for x in range(1,10) if x%2 == 0] for y in range(2)]
print(matrix)
输出
[[2, 4, 6, 8], [2, 4, 6, 8]]
展平嵌套列表
也许我们需要将一个矩阵简化成一个列表。这在计算机图形和图像处理中有时是必要的。
我们可以在 Python 中使用列表理解来做到这一点。通过调整语句中的表达式,我们可以告诉 Python 展平原始的多维列表。
例子 7:从二维走向一维
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
# welcome to Flatland
flat = [x for row in matrix for x in row]
print(flat)
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9]
让我们仔细看看这个语句:flat =[x for row in matrix for x in row]。很困惑,对吧?虽然该语句是比 for 循环更有效的展平矩阵的方式,但这是列表理解可能比它的对应物更难理解的一种情况。
下面是如何使用 for 循环和 append() 方法展平列表的方法。
示例 8:平铺列表列表
list = []
for row in matrix:
for x in row:
list.append(x)
print(list)
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9]
作为一名程序员,决定什么时候使用列表理解取决于你。风格和技巧往往是主观的。重要的是你要有意识地努力改进你的代码,让它更容易理解。
用 Python 编写列表理解语句的技巧
Python 提供了列表理解,作为创建简洁、易读的代码的一种方式。为此,我们在 Python 中加入了一个简短的使用列表理解的技巧列表。
- 列表理解比使用标准 for 循环更有效。
- 以优雅代码的名义,我们应该保持列表理解语句简短。
- 使用条件增加列表理解表达式的灵活性。
- 列表理解非常适合创建矩阵。
什么时候使用列表理解没有固定的规则。您应该将其视为 Python 工具箱中的另一个工具,可以节省您的时间和精力。随着您的进步,学习何时使用列表理解来改进您的代码将变得更加明显。
结论
列表理解是 Python 的一个与众不同的特性,可以帮助编码人员编写优雅且易于理解的程序。使用列表理解不仅节省了代码行,而且通常比其他方法更容易阅读。
虽然列表理解通常被认为比其他方法更“Pythonic 化”,例如对于循环,但这不一定是真的。Python 代码是为灵活性和效率而设计的。Python 中的每个工具都有其优点和缺点。
为了充分理解 Python 列表,我们可以添加一个条件来过滤结果。使用过滤器增加了列表理解表达式的灵活性。
如果你渴望学习更多的 Python,我们也希望如此,这里有一些额外的链接,可以帮助你成为一名编程爱好者。
相关职位
- 了解如何使用 Python 字符串串联制作更好的字符串。
- 如何使用 Python split ()将字符串拆分成单词?
Python 中文件的行数
原文:https://www.pythonforbeginners.com/basics/number-of-lines-in-a-file-in-python
文件处理是编程中最重要的操作之一。有时,我们可能需要计算文件中的行数来对其执行任何操作。在本文中,我们将看到如何用 python 计算一个文件中的行数。
使用 Python 中的 for 循环计算文件中的行数
计算文件行数的第一种方法是使用 for 循环来计算文件中所有的换行符。
为此,我们将首先在读取模式下使用open()
功能打开文件。之后,我们将遍历文件内容并检查换行符“\n
”。我们将在一个名为numberOfLines
的变量中保存对\n
字符的计数。
在执行 for 循环后,我们将在变量numberOfLines
中获得总行数。您可以在下面的示例中观察到这一点。
myFile = open("sample.txt", "r")
text = myFile.read()
print("The content of the file is:")
print(text)
numberOfLines = 0
for character in text:
if character == "\n":
numberOfLines = numberOfLines + 1
print("The number of lines in the file is:")
print(numberOfLines)
输出:
The content of the file is:
This is line 1.
This is line 2.
This is line 3.
This is line 4.
The number of lines in the file is:
4
在计算行数时,空行也用这种方法计算。这是因为我们正在计算换行符。因此,空行也将被视为新行,因为其中存在“\n
”字符。
使用 Python 中的 split()方法计算文件中的行数
我们可以使用split()
方法来计算文件中的行数,而不是检查换行符。在字符串上调用 split()
方法时,该方法将分隔符作为输入参数,并返回原始字符串的子字符串列表。
在我们的程序中,我们将使用“\n
”作为分隔符,在换行处分割文件的文本。之后,我们将使用len()
函数确定输出列表的长度。这样,我们就会找到文本文件中的行数。
myFile = open("sample.txt", "r")
text = myFile.read()
print("The content of the file is:")
print(text)
text_list = text.split("\n")
numberOfLines = len(text_list)
print("The number of lines in the file is:")
print(numberOfLines)
输出:
The content of the file is:
This is line 1.
This is line 2.
This is line 3.
This is line 4.
The number of lines in the file is:
4
使用 Python 中的 readlines()方法计算文件中的行数
当在 file 对象上调用时,readlines()
方法返回文件中的字符串列表。每个字符串由一个换行符组成。我们可以找到输出列表的长度来计算文件中的行数,如下所示。
myFile = open("sample.txt", "r")
text_list = myFile.readlines()
numberOfLines = len(text_list)
print("The number of lines in the file is:")
print(numberOfLines)
输出:
The number of lines in the file is:
4
结论
在本文中,我们讨论了用 python 计算文件行数的三种方法。要了解更多关于文件的内容,您可以阅读这篇关于 python 中的文件处理的文章。你可能也会喜欢这篇关于如何用 python 让逐行读取文本文件的文章。
Python 中的 Numpy 数组操作
原文:https://www.pythonforbeginners.com/basics/numpy-array-operations-in-python
Numpy 数组是 Python 中处理和分析数字数据的一个很好的工具。在上一篇文章中,我们讨论了创建 numpy 数组的不同方法。在本文中,我们将讨论各种 numpy 数组操作,使用这些操作可以在 Python 中分析数值数据。
Python 中 Numpy 数组的算术运算
我们可以用最简单的方式在 Python 中对 numpy 数组执行算术运算。如果你想给一个 numpy 数组的所有元素加一个数,你可以简单地把这个数加到数组本身。python 解释器将算术运算传播给数组中的所有元素,给定的数字被添加到所有数组元素中。请记住,在算术运算过程中,原始数组不会被修改。因此,您需要将算术运算的结果存储在所需的变量中。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The original array is:",arr1)
number=10
arr=arr1+10
print("The modified array is:",arr)
输出:
The original array is: [1 2 3 4 5 6 7]
The modified array is: [11 12 13 14 15 16 17]
在这里,您可以看到我们在数组中添加了数字 10。执行加法语句后,结果被广播到每个元素,值增加 10。
您还可以使用相同的语法对数组元素执行减法、乘法和除法运算。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The original array is:",arr1)
number=10
arr=arr1*10
print("The modified array is:",arr)
输出:
The original array is: [1 2 3 4 5 6 7]
The modified array is: [10 20 30 40 50 60 70]
Numpy 还允许您在两个数组的元素之间执行算术运算。您可以对一个数组的元素和另一个数组的元素执行算术运算,就像对单个元素执行相同的运算一样。
例如,如果您想将一个数组的元素添加到另一个数组的元素中,可以按如下方式进行。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The first array is:",arr1)
arr2=np.array([8,9,10,11,12,13,14])
print("The second array is:",arr2)
arr=arr1+arr2
print("The output array is:",arr)
输出:
The first array is: [1 2 3 4 5 6 7]
The second array is: [ 8 9 10 11 12 13 14]
The output array is: [ 9 11 13 15 17 19 21]
这里,我们添加了两个数组。相加后,一个数组中的元素被添加到另一个数组中相同位置的元素中。
如果要添加的数组中有不同数量的元素,程序可能会出错。因此,您需要确保数组具有相同的形状。否则,程序将会遇到如下所示的 ValueError 异常。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The first array is:",arr1)
arr2=np.array([8,9,10,11,12,13])
print("The second array is:",arr2)
arr=arr1+arr2
print("The output array is:",arr)
输出:
The first array is: [1 2 3 4 5 6 7]
The second array is: [ 8 9 10 11 12 13]
ValueError: operands could not be broadcast together with shapes (7,) (6,)
就像加法一样,您可以在两个 numpy 数组的元素之间执行减法、乘法和除法,如下所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The first array is:",arr1)
arr2=np.array([8,9,10,11,12,13,14])
print("The second array is:",arr2)
arr=arr1*arr2
print("The output array is:",arr)
输出:
The first array is: [1 2 3 4 5 6 7]
The second array is: [ 8 9 10 11 12 13 14]
The output array is: [ 8 18 30 44 60 78 98]
这里,我们执行了两个数组之间的乘法。您还可以根据需要执行其他算术运算。
Python 中使用 Numpy 数组的比较操作
我们可以一次比较一个 numpy 数组的元素和另一个元素。这看起来就像比较两个数字一样简单。例如,您可以比较 numpy 数组的数组元素是否大于某个数字,如下所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The array is:",arr1)
number=5
arr=arr1>number
print("The output array is:",arr)
输出:
The array is: [1 2 3 4 5 6 7]
The output array is: [False False False False False True True]
在这里,我们在比较之后得到一个布尔值的 numpy 数组。首先,将输入数组的元素与给定元素进行比较。对于 numpy 数组中的每个元素,比较操作的输出存储在输出 numpy 数组中。对于大于 5 的元素,我们在输出数组中得到 True。与原始数组中小于或等于 5 的元素相对应的输出数组中的元素为假。
还可以使用比较运算符对两个 numpy 数组进行元素比较。在这种情况下,将一个数组中的元素与另一个数组中相同位置的元素进行比较。比较的输出在另一个数组中返回,如下所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The first array is:",arr1)
arr2=np.array([8,9,10,11,12,13,14])
print("The second array is:",arr2)
arr=arr1>arr2
print("The output array is:",arr)
输出:
The first array is: [1 2 3 4 5 6 7]
The second array is: [ 8 9 10 11 12 13 14]
The output array is: [False False False False False False False]
这里,将第一个数组中的每个元素与第二个数组中的相应元素进行比较。然后将结果存储在输出数组中。
同样,您需要确保数组长度相等。否则,程序将会遇到 ValueError 异常。
您还可以用与一维数组类似的方式对二维 numpy 数组执行算术和比较操作。
当我们对一个带有数字的二维 numpy 数组执行算术或比较操作时,结果会传播到每个元素。
当我们在二维数组上执行元素方式的 numpy 数组操作时,操作是按元素方式执行的。在这里,您应该确保在对二维 numpy 数组执行元素算术或比较操作时,数组的形状应该相同。
找出 Numpy 数组中的最小和最大元素
要查找 numpy 数组中的最大元素,可以使用 max()方法。当在 numpy 数组上调用 max()方法时,返回数组的最大元素。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The array is:",arr1)
max_element=arr1.max()
print("The maximum element is:",max_element)
输出:
The array is: [1 2 3 4 5 6 7]
The maximum element is: 7
这里,max()方法返回数组中最大的元素。还可以使用 max()方法来查找二维 numpy 数组中的最大元素,如下所示。
import numpy as np
arr1=np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])
print("The array is:",arr1)
max_element=arr1.max()
print("The maximum element is:",max_element)
输出:
The array is: [[ 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14]]
The maximum element is: 14
要查找 numpy 数组中的最小元素,可以使用 min()方法。在 numpy 数组上调用 min()方法时,将返回最小元素,如下例所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The array is:",arr1)
min_element=arr1.min()
print("The minimum element is:",min_element)
输出:
The array is: [1 2 3 4 5 6 7]
The minimum element is: 1
您可以获取最小和最大元素的位置,而不是获取 numpy 数组中的最小值和最大值。为此,您可以使用 argmax()和 argmin()方法。
找出 Numpy 数组中最小和最大元素的索引
在 numpy 数组上调用 argmax()方法时,将返回数组中最大元素的位置,如下所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The array is:",arr1)
max_element=arr1.argmax()
print("The index of maximum element is:",max_element)
输出:
The array is: [1 2 3 4 5 6 7]
The index of maximum element is: 6
在这里,您可以看到最大的元素是索引为 6 的 7。因此,argmax()方法返回值 6。
我们可以使用 argmin()方法找到 numpy 数组中最小元素的索引。在 numpy 数组上调用 argmin()方法时,将返回数组中最小元素的位置,如下所示。
import numpy as np
arr1=np.array([1,2,3,4,5,6,7])
print("The array is:",arr1)
min_element=arr1.argmin()
print("The index of minimum element is:",min_element)
输出:
The array is: [1 2 3 4 5 6 7]
The index of minimum element is: 0
这里,最小的数字是索引为 0 的 1。因此,argmin()方法返回 0。
对于二维数组,argmax()和 argmin()方法不会返回最大元素的确切位置。相反,如果二维数组已经按行主顺序展平,则它们返回最大元素的索引。
例如,14 是下例所示数组中最大的元素。它的位置是(0,6)。但是,argmax()方法返回值 6。这是因为 argmax()方法返回元素的索引,如果它在一个扁平的数组中。argmin()方法的工作方式类似于 argmax()方法。
import numpy as np
arr1=np.array([[8,9,10,11,12,13,14],[1,2,3,4,5,6,7]])
print("The array is:",arr1)
max_element=arr1.argmax()
print("The index of maximum element is:",max_element)
输出:
The array is: [[ 8 9 10 11 12 13 14]
[ 1 2 3 4 5 6 7]]
The index of maximum element is: 6
在 Python 中对 Numpy 数组进行排序
可以使用 sort()方法对 numpy 数组进行排序。对 numpy 数组调用 sort()方法时,将对 numpy 数组中的元素进行排序,如下例所示。
import numpy as np
arr1=np.array([1,2,17,4,21,6,7])
print("The original array is:",arr1)
arr1.sort()
print("The sorted array is:",arr1)
输出:
The original array is: [ 1 2 17 4 21 6 7]
The sorted array is: [ 1 2 4 6 7 17 21]
在这里,您可以看到原始数组已经排序。sort()方法在执行后返回值 None。
如果我们在一个二维 numpy 数组上使用 sort()方法,所有的内部数组都按升序排序,如下所示。
import numpy as np
arr1=np.array([[8,9,12,11,27,34,14],[55,2,15,4,22,6,7]])
print("The original array is:",arr1)
arr1.sort()
print("The sorted array is:",arr1)
输出:
The original array is: [[ 8 9 12 11 27 34 14]
[55 2 15 4 22 6 7]]
The sorted array is: [[ 8 9 11 12 14 27 34]
[ 2 4 6 7 15 22 55]]
在上面的例子中,当我们对一个二维 numpy 数组调用 sort()方法时,您可以观察到内部的一维数组是按升序排序的。
在 Python 中切分 Numpy 数组
分割一个 numpy 数组类似于在 Python 中分割一个列表。您可以使用索引运算符对 numpy 数组执行切片操作。分割 numpy 数组的语法如下。
mySlice=myArray[start_index:end_index:interval]
这里,
- myArray 是现有的 numpy 数组。
- mySlice 是新创建的 myArray 切片。
- start_index 是 myArray 的索引,我们必须从中选择元素。
- end_index 是 myArray 的索引,在此之前我们必须选择元素。
- 间隔是 myArray 中必须包含在 mySlice 中的两个连续元素之间的间隔。
您可以使用上面的语法分割 numpy 数组,如下所示。
import numpy as np
myArr=np.array([1,2,17,4,21,6,7,12,13,14])
print("The original array is:",myArr)
mySlice=myArr[2:6:1]
print("The slice is:",mySlice)
输出:
The original array is: [ 1 2 17 4 21 6 7 12 13 14]
The slice is: [17 4 21 6]
在上面的例子中,我们将原始数组中索引 2 到 5 的元素切片到 mySlice 中。当对连续元素进行切片时,也可以省略语法中的最后一个冒号和间隔。结果会是一样的。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.array([1,2,17,4,21,6,7,12,13,14])
print("The original array is:",myArr)
mySlice=myArr[2:6]
print("The slice is:",mySlice)
输出:
The original array is: [ 1 2 17 4 21 6 7 12 13 14]
The slice is: [17 4 21 6]
在上面的例子中,我们从切片语法中省略了最后一个冒号和间隔。但是,结果与前面的示例相似。
如果您想选择从开始到特定索引的元素,您可以将起始值留空,如下所示。
import numpy as np
myArr=np.array([1,2,17,4,21,6,7,12,13,14])
print("The original array is:",myArr)
mySlice=myArr[:6:1]
print("The slice is:",mySlice)
输出:
The original array is: [ 1 2 17 4 21 6 7 12 13 14]
The slice is: [ 1 2 17 4 21 6]
在上面的例子中,我们让开始索引为空。因此,输出切片包含从索引 0 到索引 5 的元素。
要选择从特定索引到末尾的数组元素,可以将末尾索引留空,如下所示。
import numpy as np
myArr=np.array([1,2,17,4,21,6,7,12,13,14])
print("The original array is:",myArr)
mySlice=myArr[2::1]
print("The slice is:",mySlice)
输出:
The original array is: [ 1 2 17 4 21 6 7 12 13 14]
The slice is: [17 4 21 6 7 12 13 14]
在这里,我们将结束索引留空。因此,输出片段包含从索引 2 到最后的元素。
在上面的例子中,元素选自连续的索引。但是,您可以使用如下所示的间隔值以特定间隔选择元素。
import numpy as np
myArr=np.array([1,2,17,4,21,6,7,12,13,14])
print("The original array is:",myArr)
mySlice=myArr[2::2]
print("The slice is:",mySlice)
输出:
The original array is: [ 1 2 17 4 21 6 7 12 13 14]
The slice is: [17 21 7 13]
在上面的例子中,我们将 interval 的值作为 2 传递。因此,输出切片包含来自输入数组的替换元素。
在 Python 中分割二维 Numpy 数组
还可以使用索引运算符对二维 numpy 数组执行切片操作。为了对二维 numpy 数组进行切片,我们使用以下语法。
mySlice=myArray[start_row:end_row:row_interval,start_column:end_column:column_interval]
这里,术语 start_row、end_row 和 row_interval 分别表示要包括在切片中的起始行的索引、要包括在切片中的最后一行的索引以及要包括在切片中的 myArray 的两个连续行之间的间隔。
类似地,术语 start_column、end_column 和 column_interval 分别表示要包括在片中的起始列的索引、要包括在片中的最后一列的索引以及要包括在片中的 myArray 的两个连续列之间的间隔。
例如,您可以将数组的第一行切为第三行,第二列切为第四列,如下所示。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[0:4:1,1:5:1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[ 1 2 3 4]
[11 12 13 14]
[21 22 23 24]
[31 32 33 34]]
在上面的例子中,我们对从索引 0 到 3 的行和从索引 1 到 4 的列进行了切片。因此,我们从 10×10 的数组中得到一个 4×4 的数组。
如果希望包括所有行,但只选择切片中的某些列,可以将 start_row 和 end_row 值留空。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[::1,1:5:1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[ 1 2 3 4]
[11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]
[51 52 53 54]
[61 62 63 64]
[71 72 73 74]
[81 82 83 84]
[91 92 93 94]]
在这个例子中,我们选择了所有的行,但是从索引 1 到 4 中选择了列。为此,我们在切片语法中将开始和结束行索引留空。
类似地,如果您希望包含所有列,但选择切片中的某些行,可以将 start_column 和 end_column 值留空,如下所示。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[0:4:1,::1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]]
在本例中,我们选择了所有的列,但是从索引 0 到 3 中选择了行。为此,我们在切片语法中将开始和结束列索引留空。
如果希望在切片中包含从开头到某个行索引的行,可以将 start_row 留空。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[:4:1,2:5:1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[ 2 3 4]
[12 13 14]
[22 23 24]
[32 33 34]]
如果您想将某个行索引中的行包含到最后,可以将 end_row 留空,如下所示。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[3::1,2:5:1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[32 33 34]
[42 43 44]
[52 53 54]
[62 63 64]
[72 73 74]
[82 83 84]
[92 93 94]]
如果希望在切片中包含从开始到某个列索引的列,可以将 start_column 留空。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[1:4:1,:5:1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[10 11 12 13 14]
[20 21 22 23 24]
[30 31 32 33 34]]
如果您想包含从某个列索引到最后的列,可以将 end_column 留空,如下所示。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[3::1,4::1]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[34 35 36 37 38 39]
[44 45 46 47 48 49]
[54 55 56 57 58 59]
[64 65 66 67 68 69]
[74 75 76 77 78 79]
[84 85 86 87 88 89]
[94 95 96 97 98 99]]
您还可以在选定的行和列之间引入间隔,如下所示。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[3::2,4::3]
print("The slice is:")
print(mySlice)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[34 37]
[54 57]
[74 77]
[94 97]]
切片是原始 numpy 数组的视图。因此,对切片所做的任何更改也会反映在原始数组中。例如,看看下面的例子。
import numpy as np
myArr=np.arange(100).reshape((10,10))
print("The original array is:")
print(myArr)
mySlice=myArr[3::2,4::3]
print("The slice is:")
print(mySlice)
mySlice+=100
print("The original array is:")
print(myArr)
输出:
The original array is:
[[ 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 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
The slice is:
[[34 37]
[54 57]
[74 77]
[94 97]]
The original array is:
[[ 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 25 26 27 28 29]
[ 30 31 32 33 134 35 36 137 38 39]
[ 40 41 42 43 44 45 46 47 48 49]
[ 50 51 52 53 154 55 56 157 58 59]
[ 60 61 62 63 64 65 66 67 68 69]
[ 70 71 72 73 174 75 76 177 78 79]
[ 80 81 82 83 84 85 86 87 88 89]
[ 90 91 92 93 194 95 96 197 98 99]]
这里,我们只对切片进行了更改。但是,这些更改也会反映在原始数组中。这表明切片只是原始阵列的视图。因此,如果您想要对切片进行任何更改,您应该首先使用 copy()方法将其复制到另一个变量。
在 Python 中重塑 Numpy 数组
您可以使用 shape()方法重塑 numpy 数组。shape()方法有两种用法。
首先,您可以在想要整形的数组上调用 shape()方法。在 numpy 数组上调用 reshape()方法时,该方法将输出数组中的行数和列数作为其第一个和第二个输入参数。执行后,它将返回经过整形的数组,如下例所示。
import numpy as np
arr1=np.arange(20)
print("The first array is:")
print(arr1)
arr2=arr1.reshape((4,5))
print("The reshaped array is:")
print(arr2)
输出:
The first array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The reshaped array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
在上面的例子中,我们将一个有 20 个元素的一维数组改造成了一个形状为(4,5)的二维数组。
还可以将原始数组传递给 shape()方法。在这种方法中,shape()方法将原始数组作为其第一个输入参数,将包含行数和列数的元组作为其第二个输入参数。执行后,它返回如下所示的整形后的数组。
import numpy as np
arr1=np.arange(20)
print("The first array is:")
print(arr1)
arr2=np.reshape(arr1,(4,5))
print("The reshaped array is:")
print(arr2)
输出:
The first array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The reshaped array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
只要原始数组中的元素总数等于所需的整形数组中的元素数,shape()方法就能很好地工作。但是,如果原始数组中的元素总数小于或大于所需输出数组中的元素数,则程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(20)
print("The first array is:")
print(arr1)
arr2=np.reshape(arr1,(4,7))
print("The reshaped array is:")
print(arr2)
输出:
ValueError: cannot reshape array of size 20 into shape (4,7)
由 shape()方法返回的数组是原始数组的视图。因此,对新数组的任何更改都会导致对原始数组的修改。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(20)
print("The first array is:")
print(arr1)
arr2=np.reshape(arr1,(4,5))
print("The reshaped array is:")
print(arr2)
arr2+=100
print("The first array is:")
print(arr1)
输出:
The first array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The reshaped array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
The first array is:
[100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
118 119]
在这里,您可以观察到在重新整形的二维数组中所做的更改在原始的一维数组中也是可见的。这证明了整形后的数组只是原始数组的视图。因此,如果您想要对整形后的数组进行更改,如果您不想对原始数组进行更改,您应该首先考虑将其复制到一个新变量中。
在 Python 中展平 Numpy 数组
要展平 numpy 数组,可以将值-1 作为维度传递给 shape()方法,如下所示。
import numpy as np
arr1=np.arange(20).reshape(4,5)
print("The first array is:")
print(arr1)
arr2=np.reshape(arr1,-1)
print("The flattened array is:")
print(arr2)
输出:
The first array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
The flattened array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
可以使用 flatten()方法来展平 numpy 数组,而不使用 shape()方法。flatten()方法在二维 numpy 数组上调用时,会返回数组的平面一维视图。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(20).reshape(4,5)
print("The first array is:")
print(arr1)
arr2=arr1.flatten()
print("The flattened array is:")
print(arr2)
输出:
The first array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
The flattened array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
flatten()方法返回一个副本,而不是一个视图。要理解这一点,请看下面的例子。
import numpy as np
arr1=np.arange(20).reshape(4,5)
print("The first array is:")
print(arr1)
arr2=arr1.flatten()
print("The flattened array is:")
print(arr2)
arr2+=50
print("The first array is:")
print(arr1)
输出:
The first array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
The flattened array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The first array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
在这里,您可以看到对展平数组所做的更改没有反映在原始数组中。在 reshape()方法中不会发生这种情况。
reshape()方法返回原始数组的视图,对经过整形的数组所做的任何更改在原始数组中都是可见的。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(20).reshape(4,5)
print("The first array is:")
print(arr1)
arr2=arr1.reshape(-1)
print("The flattened array is:")
print(arr2)
arr2+=50
print("The first array is:")
print(arr1)
输出:
The first array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
The flattened array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The first array is:
[[50 51 52 53 54]
[55 56 57 58 59]
[60 61 62 63 64]
[65 66 67 68 69]]
因此,如果希望在修改展平的数组时保持原始数组不变,应该使用 flatten()方法而不是 shape()方法来展平 numpy 数组。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
在 Python 中复制 Numpy 数组
因为 shape()方法和 flatten()方法返回原始 NumPy 数组的视图,所以如果不想更改原始数组,就不能修改视图。在这种情况下,可以使用 copy()方法将视图复制到另一个数组中。
当在 numpy 数组上调用 copy()方法时,它返回原始数组的副本。如果对复制阵列进行任何更改,这些更改不会反映在原始阵列中。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(20)
print("The first array is:")
print(arr1)
arr2=arr1.copy()
print("The copied array is:")
print(arr2)
输出:
The first array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
The copied array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
结论
在本文中,我们讨论了 Python 中不同的 numpy 数组操作。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何创建熊猫数据框架的文章。您可能也会喜欢这篇关于 Python 中的字符串操作的文章。
模块:os.stat()
操作系统统计
要在给定的路径上执行 stat 系统调用,我们可以使用 os 的 os.stat()函数。
首先导入 os 模块,然后简单地指定要在其上执行系统调用的文件的路径。
例子
让我们看一个如何使用 os.stat 函数的例子
import os
print "-" * 30
print "os.stat = status of a file " , os.stat('/usr/bin/vi')
print "-" * 30
操作系统模块:概述
操作系统模块
Python 中的 OS 模块提供了一种使用操作系统相关功能的方式。
os 模块还提供查找关于您的位置或过程的重要信息的功能。在这篇文章中,我将展示其中的一些功能。
操作系统功能
import os
os.system() Executing a shell command
os.environ() Get the users environment
os.getcwd() Returns the current working directory.
os.getgid() Return the real group id of the current process.
os.getuid() Return the current process’s user id.
os.getpid() Returns the real process ID of the current process.
os.uname() Return information identifying the current OS.
os.chroot(path) Change the root directory of the current process to path
os.listdir(path) Return a list of the entries in the directory by path.
os.mkdir(path) Create a directory named path with numeric mode mode
os.makedirs(path) Recursive directory creation function
os.remove(path) Remove (delete) the file path
os.removedirs(path) Remove directories recursively
os.rename(src, dst) Rename the file or directory src to dst
os.rmdir(path) Remove (delete) the directory path
关于 OS 模块的更多用法,请参见官方的 Python 文档。
OS。Python 中的 Walk 和 Fnmatch
原文:https://www.pythonforbeginners.com/code-snippets-source-code/os-walk-and-fnmatch-in-python
概观
在之前的一篇文章中,我描述了如何使用 OS.walk,并展示了一些如何在脚本中使用它的例子。
在本文中,我将展示如何使用 os.walk()模块函数遍历目录树,以及使用 fnmatch 模块匹配文件名。
OS.walk 是什么?
它通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。
对于以目录顶层为根的树中的每个目录(包括顶层本身),它产生一个三元组(目录路径、目录名、文件名)。
dirpath # 是一个字符串,指向目录的路径。
目录名# 是目录路径中子目录的名称列表(不包括'.'和'..').
filenames # 是 dirpath 中非目录文件的名称列表。
请注意,列表中的名称不包含路径组件。
要在 dirpath 中获取文件或目录的完整路径(以 top 开头),请执行 os.path.join(dirpath,name)。更多信息,请参见 Python 文档。
什么是 Fnmatch
fnmatch 模块将文件名与诸如 Unix shells 所使用的 glob 样式的模式进行比较。
这些和更复杂的正则表达式规则不一样。纯粹是字符串匹配操作。
如果您发现使用不同的模式样式更方便,例如正则表达式,那么只需使用正则表达式操作来匹配您的文件名。http://www.doughellmann.com/PyMOTW/fnmatch/
它是做什么的?
fnmatch 模块用于通配符模式匹配。
简单匹配
fnmatch()将单个文件名与一个模式进行比较,并返回一个布尔值来指示它们是否匹配。当操作系统使用区分大小写的文件系统时,比较是区分大小写的。
过滤
要测试文件名序列,可以使用 filter()。它返回与模式参数匹配的名称列表。
查找所有 mp3 文件
这个脚本将从根路径(“/”)中搜索*.mp3 文件
import fnmatch
import os
rootPath = '/'
pattern = '*.mp3'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print( os.path.join(root, filename))
在计算机中搜索特定文件
此脚本使用带有过滤器的“os.walk”和“fnmatch”在硬盘中搜索所有图像文件
import fnmatch
import os
images = ['*.jpg', '*.jpeg', '*.png', '*.tif', '*.tiff']
matches = []
for root, dirnames, filenames in os.walk("C:\"):
for extensions in images:
for filename in fnmatch.filter(filenames, extensions):
matches.append(os.path.join(root, filename))
有许多其他(更快)的方法可以做到这一点,但是现在您已经了解了它的基本原理。
更多阅读
http://Rosetta code . org/wiki/Walk _ a _ directory/Recursively # Python
使用 fnmatch 的 stack overflow oswalk
用 Python 包装
原文:https://www.pythonforbeginners.com/basics/packing-in-python
打包是 python 中的一种技术,我们用它将几个值放入一个迭代器中。如果我们从字面意义上谈论打包,就像我们在现实世界中把某些项目打包到一个盒子里一样,在 python 中我们把某些变量打包到一个 iterable 中。在本文中,我们将研究如何执行打包并在我们的程序中使用它。
如何在 Python 中进行打包?
我们可以通过使用简单的语法声明列表或元组等可重复项来执行打包,也可以使用星号操作符来打包。操作符被用作将可变量解包成变量的操作符,但是它允许我们将多个变量打包成一个变量。
例如,假设我们有三个变量 num1,num2,num3。我们可以将它们打包成一个元组,如下所示。
num1=1
num2=2
num3=3
myTuple=(num1,num2,num3)
或者我们可以将它们打包成一个列表,如下所示。
num1=1
num2=2
num3=3
myList=[num1,num2,num3]
或者,我们可以使用*运算符将这些数字打包在一起,如下所示。
num1=1
num2=2
num3=3
*num,=num1,num2,num3
我们在*num 后面使用了逗号“,”因为赋值操作的左边必须是元组或列表,否则将会遇到错误。
在左侧,当我们使用*运算符时,我们还可以有其他变量,这些变量可以被赋值。例如,我们可以将两个数字打包到一个变量中,然后将第三个数字赋给另一个变量,如下所示。
num1=1
num2=2
num3=3
*num,myNum=num1,num2,num3
在上面的例子中,我们必须记住 myNum 是一个强制变量,必须给它赋值,而*num 可以不赋值。这里,num3 将被分配给 myNum,num1 和 num2 将被打包在列表 num 中。
在传递参数中使用打包
当我们不知道有多少参数将被传递给一个函数时,我们使用打包来处理这种情况。我们可以声明最初的几个变量,然后使用星号操作符将剩余的参数打包到一个变量中,如下所示。
def sumOfNumbers(num1,num2,*nums):
temp=num1+num2
for i in nums:
temp=temp+i
return temp
在上面的示例中,当只传递两个数字来计算它们的和时,nums 保持为空,并且返回两个数字的和。当我们向函数传递两个以上的数字时,第一个和第二个参数被分配给 num1 和 num2,参数中的其余数字将被打包到 nums 中,其行为类似于一个列表。之后,将计算这些数字的总和。
通过打包收集多个值
在编写程序时,可能会有这样的情况,我们希望将一个序列或字符串或一个 iterable 分成许多部分。例如,我们可能需要执行一个 python 字符串分割操作,从包含名字的字符串中收集一个人的名字。现在,如果我们不知道一个人的名字中可能有多少个单词,我们可以将名字收集到一个变量中,并将其余的单词收集到一个变量中,如下所示。
name="Joseph Robinette Biden Jr"
first_name, *rest_name=name.split()
print("Full Name:")
print(name)
print("First Name:")
print(first_name)
print("Rest Parts of Name:")
print(rest_name)
输出:
Full Name:
Joseph Robinette Biden Jr
First Name:
Joseph
Rest Parts of Name:
['Robinette', 'Biden', 'Jr']
在 python 中使用打包合并两个可重复项
我们可以在 python 中使用星号运算符(*)来合并列表、元组、集合和字典等不同的可迭代对象。
为了将两个元组合并成一个元组,我们可以使用打包。我们可以使用星号运算符合并两个元组,如下所示。
print("First Tuple is:")
tuple1=(1,2,3)
print(tuple1)
print("Second Tuple is:")
tuple2=(4,5,6)
print(tuple2)
print("Merged tuple is:")
myTuple=(*tuple1,*tuple2)
print(myTuple)
输出:
First Tuple is:
(1, 2, 3)
Second Tuple is:
(4, 5, 6)
Merged tuple is:
(1, 2, 3, 4, 5, 6)
就像元组一样,我们可以如下合并两个列表。
print("First List is:")
list1=[1,2,3]
print(list1)
print("Second List is:")
list2=[4,5,6]
print(list2)
print("Merged List is:")
myList=[*list1,*list2]
print(myList)
输出:
First List is:
[1, 2, 3]
Second List is:
[4, 5, 6]
Merged List is:
[1, 2, 3, 4, 5, 6]
我们还可以使用打包将两个或多个字典合并成一个 python 字典。对于字典,使用字典解包操作符**来解包两个初始字典,然后将它们打包到第三个字典中。这可以从下面的例子中理解。
print("First Dictionary is:")
dict1={1:1,2:4,3:9}
print(dict1)
print("Second Dictionary is:")
dict2={4:16,5:25,6:36}
print(dict2)
print("Merged Dictionary is:")
myDict={**dict1,**dict2}
print(myDict)
输出:
First Dictionary is:
{1: 1, 2: 4, 3: 9}
Second Dictionary is:
{4: 16, 5: 25, 6: 36}
Merged Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
结论
在本文中,我们学习了 python 中的打包,并实现了不同的程序来理解使用星号(*)操作符的打包操作的用例。请继续关注更多内容丰富的文章。
Python 中的熊猫数据帧索引
原文:https://www.pythonforbeginners.com/basics/pandas-dataframe-index-in-python
Pandas dataframes 是 Python 中数据分析和机器学习任务最常用的数据结构之一。在本文中,我们将讨论如何从 pandas 数据帧中创建和删除索引。我们还将讨论 pandas 数据帧中的多级索引,以及如何使用数据帧索引来访问数据帧中的元素。
什么是熊猫数据框架指数?
就像 dataframe 有列名一样,您可以将索引视为行标签。当我们创建数据帧时,数据帧的行被赋予从 0 开始的索引,直到行数减 1,如下所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
A B C
0 1 2 3
1 3 55 34
2 12 32 45
The index is:
[0, 1, 2]
创建熊猫数据框架时创建索引
您还可以在创建数据框架时创建自定义索引。为此,您可以使用DataFrame()
函数的index
参数。index
参数接受一个值列表,并将这些值指定为数据帧中行的索引。您可以在下面的示例中观察到这一点。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"],index=[101,102,103])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
A B C
101 1 2 3
102 3 55 34
103 12 32 45
The index is:
[101, 102, 103]
在上面的例子中,我们已经使用列表[101, 102, 103]
和DataFrame()
函数的index
参数创建了数据帧的索引。
这里,您需要确保传递给参数index
的列表中的元素数量应该等于 dataframe 中的行数。否则,程序会遇到如下所示的值错误异常。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"],index=[101,102,103,104])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
ValueError: Length of values (3) does not match length of index (4)
在上面的例子中,您可以观察到我们将列表中的 4 个元素传递给了 index 参数。然而,数据帧只有三行。因此,程序会遇到 Python ValueError 异常。
加载 CSV 文件时创建数据帧索引
如果您正在创建一个 csv 文件的数据帧,并希望将 csv 文件的一列作为数据帧索引,您可以使用read_csv()
函数中的index_col
参数。
index_col
参数将列名作为其输入参数。执行read_csv()
函数后,指定的列被指定为数据帧的索引。您可以在下面的示例中观察到这一点。
myDf=pd.read_csv("samplefile.csv",index_col="Class")
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
您还可以将列名在列列表中的位置而不是它的名称作为输入参数传递给index_col
参数。例如,如果想将熊猫数据帧的第一列作为索引,可以将 0 传递给DataFrame()
函数中的index_col
参数,如下所示。
myDf=pd.read_csv("samplefile.csv",index_col=0)
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
这里,Class
列是 csv 文件中的第一列。因此,它被转换成数据帧的索引。
index_col
参数也接受多个值作为它们的输入。我们已经在数据帧中的多级索引一节中讨论了这一点。
创建熊猫数据框架后创建索引
当创建数据帧时,数据帧的行被分配从 0 开始直到行数减 1 的索引。但是,我们可以使用 index 属性为 dataframe 创建自定义索引。
为了在 pandas 数据帧中创建自定义索引,我们将为数据帧的 index 属性分配一个索引标签列表。执行赋值语句后,将为数据帧创建一个新索引,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf.index=[101,102,103,104,105,106,107,108]
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Class Roll Name
101 1 11 Aditya
102 1 12 Chris
103 1 13 Sam
104 2 1 Joel
105 2 22 Tom
106 2 44 Samantha
107 3 33 Tina
108 3 34 Amy
The index is:
[101, 102, 103, 104, 105, 106, 107, 108]
在这里,您可以看到我们将一个包含从 101 到 108 的数字的列表分配给了 dataframe 的 index 属性。因此,列表的元素被转换成数据帧中行的索引。
请记住,列表中索引标签的总数应该等于数据帧中的行数。否则,程序将遇到 ValueError 异常。
将数据帧的列转换为索引
我们也可以使用列作为数据帧的索引。为此,我们可以使用set_index()
方法。在 dataframe 上调用set_index()
方法时,该方法将列名作为其输入参数。执行后,它返回一个新的 dataframe,并将指定的列作为其索引,如下例所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf=myDf.set_index("Class")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
在上面的例子中,我们使用了set_index()
方法从数据帧的现有列而不是新序列中创建索引。
熊猫数据帧的变化指数
您可以使用set_index()
方法更改数据帧的索引列。为此,您只需要将新索引列的列名作为输入传递给set_index()
方法,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf=myDf.set_index("Class")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
print("The modified dataframe is:")
newDf=myDf.set_index("Roll")
print(newDf)
print("The index is:")
index=list(newDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
The modified dataframe is:
Name
Roll
11 Aditya
12 Chris
13 Sam
1 Joel
22 Tom
44 Samantha
33 Tina
34 Amy
The index is:
[11, 12, 13, 1, 22, 44, 33, 34]
如果要将一个序列作为新的索引分配给数据帧,可以将该序列分配给 pandas 数据帧的 index 属性,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf=myDf.set_index("Class")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
print("The modified dataframe is:")
myDf.index=[101, 102, 103, 104, 105, 106, 107, 108]
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
The modified dataframe is:
Roll Name
101 11 Aditya
102 12 Chris
103 13 Sam
104 1 Joel
105 22 Tom
106 44 Samantha
107 33 Tina
108 34 Amy
The index is:
[101, 102, 103, 104, 105, 106, 107, 108]
当我们更改数据帧的索引列时,现有的索引列将从数据帧中删除。因此,在更改索引列之前,应该首先将索引列存储到数据帧的新列中。否则,您将丢失数据帧中存储在索引列中的数据。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf=myDf.set_index("Class")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
print("The modified dataframe is:")
myDf["Class"]=myDf.index
myDf.index=[101, 102, 103, 104, 105, 106, 107, 108]
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
The index is:
[1, 1, 1, 2, 2, 2, 3, 3]
The modified dataframe is:
Roll Name Class
101 11 Aditya 1
102 12 Chris 1
103 13 Sam 1
104 1 Joel 2
105 22 Tom 2
106 44 Samantha 2
107 33 Tina 3
108 34 Amy 3
The index is:
[101, 102, 103, 104, 105, 106, 107, 108]
在这里,您可以看到,在更改数据帧的索引之前,我们首先将索引存储到了Class
列中。在前一个例子中,我们没有这样做。因此,Class
列中的数据丢失。
在熊猫数据框架中创建多级索引
您还可以在数据帧中创建多级索引。多级索引有助于您访问分层数据,如具有不同抽象级别的人口普查数据。我们可以在创建数据帧的同时以及在创建数据帧之后创建多级索引。这一点讨论如下。
创建数据框架时创建多级索引
要使用 dataframe 的不同列创建多级索引,可以使用read_csv()
函数中的index_col
参数。index_col
参数接受必须用作索引的列的列表。列表中赋予index_col
参数的列名从左到右的顺序是从最高到最低的索引级别。在执行了read_csv()
函数后,你将得到一个多级索引的数据帧,如下例所示。
myDf=pd.read_csv("samplefile.csv",index_col=["Class","Roll"])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
The index is:
[(1, 11), (1, 12), (1, 13), (2, 1), (2, 22), (2, 44), (3, 33), (3, 34)]
在上面的示例中,Class
列包含第一级索引,Roll
列包含第二级索引。要从 dataframe 中访问元素,您需要知道任意行的两个级别的索引。
除了使用列名,您还可以将列名在列列表中的位置而不是其名称作为输入参数传递给index_col
参数。例如,您可以将 dataframe 的第一列和第三列指定为其索引,如下所示。
myDf=pd.read_csv("samplefile.csv",index_col=[0,1])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
The index is:
[(1, 11), (1, 12), (1, 13), (2, 1), (2, 22), (2, 44), (3, 33), (3, 34)]
创建数据帧后创建多级索引
您还可以在使用set_index()
方法创建数据帧之后创建多级索引。为此,您只需要将列名列表传递给set_index()
方法。同样,列表中赋予index_col
参数的列名从左到右的顺序是从最高到最低的索引级别,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
myDf=myDf.set_index(["Class","Roll"])
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
The index is:
[(1, 11), (1, 12), (1, 13), (2, 1), (2, 22), (2, 44), (3, 33), (3, 34)]
您需要记住,set_index()
方法会删除现有的索引列。如果要保存存储在索引列中的数据,应该在创建新索引之前将数据复制到另一列中。
从熊猫数据帧中删除索引
要从 pandas 数据帧中删除索引,可以使用reset_index()
方法。在 dataframe 上调用reset_index()
方法时,会返回一个没有任何索引列的新 dataframe。如果现有索引是特定的列,则该列将再次转换为普通列,如下所示。
myDf=pd.read_csv("samplefile.csv",index_col=[0,1])
print("The dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
myDf=myDf.reset_index()
print("The modified dataframe is:")
print(myDf)
print("The index is:")
index=list(myDf.index)
print(index)
输出:
The dataframe is:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
The index is:
[(1, 11), (1, 12), (1, 13), (2, 1), (2, 22), (2, 44), (3, 33), (3, 34)]
The modified dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
The index is:
[0, 1, 2, 3, 4, 5, 6, 7]
结论
在这篇文章中,我们讨论了如何创建熊猫数据帧索引。此外,我们还创建了多级索引,并学习了如何从熊猫数据帧中删除索引。要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中的列表理解的文章。如果你对机器学习感兴趣,你可以阅读这篇关于机器学习中的正则表达式的文章。
请继续关注更多内容丰富的文章。
快乐学习!
Python 中的熊猫系列数据结构
原文:https://www.pythonforbeginners.com/basics/pandas-series-data-structure-in-python
Python 中使用系列数据结构处理一维数据。在本文中,我们将讨论如何使用 pandas 模块创建一个系列,它的属性,以及使用示例的操作。
熊猫系列是什么?
你可以把熊猫系列看作是一个列表和一个字典的组合。在一个序列中,所有元素都按顺序存储,您可以使用索引来访问它们。
就像我们使用键名从 python 字典中访问值一样,您可以为 pandas 系列中的元素分配标签,并使用标签来访问它们。
用 Python 创建熊猫系列
为了创建一个系列,我们使用pandas.Series()
函数。它将一个列表或一个 python 字典作为它的输入参数,并返回一个序列。我们已经在下面的章节中讨论了Series()
函数的使用。
将 Python 列表转换为熊猫系列
您可以使用列表元素创建熊猫系列。Series()
方法将列表作为其输入参数,并返回一个 Series 对象,如下所示。
import pandas as pd
names = ['Aditya', 'Chris', 'Joel']
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
输出:
The input list is:
['Aditya', 'Chris', 'Joel']
The series is:
0 Aditya
1 Chris
2 Joel
dtype: object
在输出中,您可以看到列表元素位于第二列。数列的第一列由数列的索引组成。索引用于访问序列中的元素。
默认情况下,序列中的索引从 0 开始。但是,您可以使用Series()
函数中的 index 参数将索引明确分配给序列。
index 参数接受一个索引值列表,并将索引分配给序列中的元素,如下所示。
import pandas as pd
names = ['Aditya', 'Chris', 'Joel']
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names, index=["A","B", "C"])
print(mySeries)
输出:
The input list is:
['Aditya', 'Chris', 'Joel']
The series is:
A Aditya
B Chris
C Joel
dtype: object
这里,我们将列表["A", "B", "C"]
传递给了函数Series()
的索引参数。因此,“A”、“B”和“C”被指定为系列行的索引。
这里,您需要记住,索引的数量应该等于序列中元素的数量。否则,程序将出现如下所示的错误。
import pandas as pd
names = ['Aditya', 'Chris', 'Joel']
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names, index=["A","B", "C", "D"])
print(mySeries)
输出:
The input list is:
['Aditya', 'Chris', 'Joel']
The series is:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_6004/861141107.py in <module>
4 print(names)
5 print("The series is:")
----> 6 mySeries=pd.Series(names, index=["A","B", "C", "D"])
7 print(mySeries)
ValueError: Length of values (3) does not match length of index (4)
在上面的例子中,我们向 index 参数传递了一个包含四个元素的列表。但是,这个系列只有三个元素。因此,程序会遇到 ValueError 异常。
除了将标签列表传递给Series()
函数,您还可以将标签列表分配给序列的 index 属性。这将为系列创建索引标签,如下所示。
import pandas as pd
names = ['Aditya', 'Chris', 'Joel']
print("The input list is:")
print(names)
print("Series before index creation:")
mySeries=pd.Series(names)
print(mySeries)
mySeries.index=["A","B", "C"]
print("Series after index creation:")
print(mySeries)
输出:
The input list is:
['Aditya', 'Chris', 'Joel']
Series before index creation:
0 Aditya
1 Chris
2 Joel
dtype: object
Series after index creation:
A Aditya
B Chris
C Joel
dtype: object
在本例中,我们没有使用 index 参数,而是使用 Series 对象的 index 属性为系列中的行创建索引。
将 Python 字典转换为 Python 中的系列
做一个带标签的熊猫系列,也可以用 python 字典。当我们将字典传递给Series()
函数时,字典的键就变成了索引标签。对应于某个键的值成为序列中的数据值。您可以在下面的示例中观察到这一点。
import pandas as pd
names = {"A":'Aditya', "B":'Chris', "C":'Joel'}
print("The input dictionary is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
输出:
The input dictionary is:
{'A': 'Aditya', 'B': 'Chris', 'C': 'Joel'}
The series is:
A Aditya
B Chris
C Joel
dtype: object
在上面的例子中,您可以观察到字典的键已经变成了索引标签。字典的相应值被分配给与索引相关联的行。
除了列表或字典,您还可以将一个元组或其他有序的可迭代对象传递给Series()
函数来创建 pandas 系列。但是,您不能将一个无序的可迭代对象(比如集合)作为输入传递给Series()
函数来创建一个序列。这样做将使你的程序运行到如下所示的错误中。
import pandas as pd
names = {'Aditya', 'Chris', 'Joel'}
print("The input set is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
输出:
The input set is:
{'Joel', 'Aditya', 'Chris'}
The series is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_6004/4101083988.py in <module>
4 print(names)
5 print("The series is:")
----> 6 mySeries=pd.Series(names)
7 print(mySeries)
TypeError: 'set' type is unordered
这里,我们将一个集合传递给了Series()
函数。因此,程序运行到 Python TypeError 异常,并显示 set type 是无序的消息。
熊猫系列中元素的数据类型
当从列表或字典的元素创建序列时,序列中元素的数据类型是根据输入元素的数据类型决定的。
例如,如果您将一个整数列表传递给Series()
函数,那么序列的结果数据类型将是如下所示的int64
。
import pandas as pd
names = [1,2,3,4]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2, 3, 4]
The series is:
0 1
1 2
2 3
3 4
dtype: int64
The datatype of series elements is:
int64
上述条件也适用于浮点数。然而,当我们将一个 floats 和 int 的列表传递给Series()
函数时,序列中的结果数据集是float64
,因为所有的元素都被转换为最高级别的兼容数据类型。您可以在下面的示例中观察到这一点。
import pandas as pd
names = [1,2,3.1,4.2]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2, 3.1, 4.2]
The series is:
0 1.0
1 2.0
2 3.1
3 4.2
dtype: float64
The datatype of series elements is:
float64
在上面的例子中,数据类型被写成float64
和int64
,因为程序是在 64 位机器上执行的。如果你在 32 位机器上运行程序,你将得到 int32 和 float32 的数据类型。所以,如果你得到这种类型的输出,不用担心。
当您将字符串列表传递给Series()
函数时,序列元素的结果数据类型是"object
"而不是字符串,如下例所示。
import pandas as pd
names = ['Aditya', 'Chris', 'Joel']
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
['Aditya', 'Chris', 'Joel']
The series is:
0 Aditya
1 Chris
2 Joel
dtype: object
The datatype of series elements is:
object
当我们将包含整型、浮点型和字符串的列表传递给Series()
函数时,series 元素的结果数据类型是“object
”。
import pandas as pd
names = [1, 2.2, 'Joel']
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2.2, 'Joel']
The series is:
0 1
1 2.2
2 Joel
dtype: object
The datatype of series elements is:
object
元素被赋予 object 数据类型,因为我们可以在 object 数据类型中包含任何值。将值存储为对象数据类型有助于解释器以简单的方式处理元素的数据类型。
熊猫系列中的无类型值
在创建 series 对象时,当我们将一个包含值 None 的列表传递给Series()
函数时,会出现一种特殊情况。
当我们将包含值None
的字符串列表传递给Series()
函数时,该序列的数据类型是“object
”。这里,值None
被存储为对象类型。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
The datatype of series elements is:
object
然而,当我们传递一个包含值None
的整数列表时,None
被转换为NaN
,这是一个不存在的值的浮点表示。因此,序列的数据类型变成了float64
。类似地,当我们传递浮点数列表中的值None
时,None
被转换为NaN
。
import pandas as pd
names = [1, 2.2, 3.2, None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2.2, 3.2, None]
The series is:
0 1.0
1 2.2
2 3.2
3 NaN
dtype: float64
The datatype of series elements is:
float64
在前面的示例中,None
被存储为一个NoneType
对象,因为该系列包含一个字符串。在本例中,None
被存储为浮点值NaN
,因为该系列只包含数字。因此,可以说 python 解释器根据现有元素的兼容性为系列选择了最佳数据类型。
当我们将包含整型、浮点型和字符串的列表传递给String()
函数时,None
被存储为对象类型。你可以在上面的例子中观察到这一点。
import pandas as pd
names = [1, 2.2, 3.2, None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
print("The datatype of series elements is:")
print(mySeries.dtype)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
The datatype of series elements is:
object
使用索引运算符从系列中访问数据
您可以使用索引运算符访问序列中的数据,就像访问列表元素一样。为此,您可以在索引操作符中传递 series 元素的位置,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
index=2
myVal=mySeries[index]
print("Element at index {} is {}".format(index,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
Element at index 2 is Aditya
如果已经为索引分配了标签,则可以使用索引运算符中的标签来访问序列元素。这类似于我们如何使用键和索引操作符来访问字典的值。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names, index=["A","B", "C", "D"])
print(mySeries)
index="B"
myVal=mySeries[index]
print("Element at index {} is {}".format(index,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
Element at index B is 2.2
使用索引运算符时,当整数用作索引标签时,不能使用元素的位置来访问元素。例如,考虑以下示例中的系列。这里,索引标签是整数。因此,我们不能使用索引 0 来访问序列中的第一个元素,也不能使用索引 1 来访问序列中的第二个元素,依此类推。这样做会导致如下所示的 KeyError 异常。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names, index=[4,5,6,7])
print(mySeries)
index=0
myVal=mySeries[index]
print("Element at index {} is {}".format(index,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
4 1
5 2.2
6 Aditya
7 None
dtype: object
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/tmp/ipykernel_6004/208185265.py in <module>
7 print(mySeries)
8 index=0
----> 9 myVal=mySeries[index]
10 print("Element at index {} is {}".format(index,myVal))
KeyError: 0
因此,在这些情况下,您只能在使用索引操作符访问元素时使用索引标签。但是,您可以使用 pandas 系列对象的iloc
属性,通过它们在系列中的位置来访问元素。
使用 Python 中的 iloc 访问系列数据
iloc
属性的功能类似于列表索引。iloc
属性包含一个_iLocIndexer
对象,您可以用它来访问序列中的数据。您可以简单地使用方括号内的位置和iloc
属性来访问熊猫系列的元素,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
position=0
myVal=mySeries.iloc[position]
print("Element at position {} is {}".format(position,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
Element at position 0 is 1
如果您使用整数作为系列的索引标签,这对iloc
属性的工作没有任何影响。iloc
属性用于访问某个位置的列表。因此,我们使用什么索引并不重要,iloc
属性以同样的方式工作。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=[1,2,3,4])
print(mySeries)
position=0
myVal=mySeries.iloc[position]
print("Element at position {} is {}".format(position,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
1 1
2 2.2
3 Aditya
4 None
dtype: object
Element at position 0 is 1
使用 Python 中的 loc 属性从系列中访问数据
系列的loc
属性的工作方式类似于 python 字典的键。loc
属性包含一个_LocIndexer
对象,您可以用它来访问序列中的数据。您可以使用方括号内的索引标签和loc
属性来访问 pandas 系列的元素,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
index="A"
myVal=mySeries.loc[index]
print("Element at index {} is {}".format(index,myVal))
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
Element at index A is 1
将数据插入熊猫系列
要将单个元素插入到序列中,可以使用loc
属性或append()
方法。
要将数据插入到带有索引标签的序列中,可以使用loc
属性。在这里,我们将以在 python 字典中添加新的键-值对的相同方式为系列分配标签和值。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
index="D"
mySeries.loc[index]=1117
print("The modified series is:")
print(mySeries)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
A 1
B 2.2
C Aditya
D 1117
dtype: object
append()
方法用于将一个系列追加到另一个系列。当在一个系列上调用时,它将另一个系列作为其输入参数,将其附加到原始系列,并返回一个包含两个系列中元素的新系列。
为了将一个元素插入到一个序列中,我们将首先用给定的元素创建一个新的序列。之后,我们将使用下面的例子所示的append()
方法将新的序列添加到现有的序列中。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
newSeries=pd.Series([1117])
mySeries=mySeries.append(newSeries)
print("The modified series is:")
print(mySeries)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
A 1
B 2.2
C Aditya
D None
0 1117
dtype: object
您可以观察到输出序列的索引没有按顺序排列。这是因为新系列和现有系列的索引已经与元素合并。为了保持索引的顺序,您可以在如下所示的append()
函数中使用ignore_index=True
参数。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
newSeries=pd.Series([1117])
mySeries=mySeries.append(newSeries, ignore_index=True )
print("The modified series is:")
print(mySeries)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
0 1
1 2.2
2 Aditya
3 None
4 1117
dtype: object
如果现有序列具有索引标签,并且要插入的数据也包含索引的特定标签,您也可以使用append()
方法向序列添加新元素,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The input list is:")
print(names)
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
newSeries=pd.Series([1117],index=["P"])
mySeries=mySeries.append(newSeries)
print("The modified series is:")
print(mySeries)
输出:
The input list is:
[1, 2.2, 'Aditya', None]
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
A 1
B 2.2
C Aditya
D None
P 1117
dtype: object
append()
方法已经被弃用,它将从熊猫的未来版本中移除(我目前使用的是熊猫 1.4.3)。如果您正在使用append()
方法并得到错误,那么您可能正在使用一个新版本的 pandas。因此,寻找一种替代方法来将元素添加到系列中。
建议阅读: K-Means 使用 Python 中的 sklearn 模块进行聚类
在 Python 中删除熊猫系列的数据
要在 Python 中删除序列中的数据,可以使用drop()
方法。在 series 对象上调用时,drop()
方法将一个索引标签或一组索引标签作为其输入参数。执行后,它会在删除指定索引处的数据后返回一个新序列。
要从具有索引标签的序列中删除单个元素,可以将索引标签传递给如下所示的drop()
函数。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
mySeries=mySeries.drop("A")
print("The modified series is:")
print(mySeries)
输出:
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
B 2.2
C Aditya
D None
dtype: object
要删除多个索引标签处的元素,可以将索引标签列表传递给如下所示的drop()
方法。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
mySeries=mySeries.drop(["A","D"])
print("The modified series is:")
print(mySeries)
输出:
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
B 2.2
C Aditya
dtype: object
在上面的例子中,原始系列没有被修改。要删除原始序列中的元素,可以使用如下所示的drop()
方法中的inplace=True
参数。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
mySeries.drop(["A","D"], inplace=True)
print("The modified series is:")
print(mySeries)
输出:
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
B 2.2
C Aditya
dtype: object
要从没有索引标签的序列中删除元素,可以使用元素在索引处的位置,并将其传递给如下所示的drop()
方法。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
mySeries.drop(0, inplace=True)
print("The modified series is:")
print(mySeries)
输出:
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
The modified series is:
1 2.2
2 Aditya
3 None
dtype: object
要删除多个位置的元素,可以将索引列表传递给如下所示的drop()
方法。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
mySeries.drop([0,1], inplace=True)
print("The modified series is:")
print(mySeries)
输出:
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
The modified series is:
2 Aditya
3 None
dtype: object
更新熊猫系列中的数据
要更新给定索引处的元素,可以使用索引操作符和赋值操作符,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names)
print(mySeries)
mySeries[0]=12345
print("The modified series is:")
print(mySeries)
输出:
The series is:
0 1
1 2.2
2 Aditya
3 None
dtype: object
The modified series is:
0 12345
1 2.2
2 Aditya
3 None
dtype: object
对于具有索引标签的系列,可以将索引标签与赋值运算符一起使用,如下所示。
import pandas as pd
names = [1, 2.2, "Aditya", None]
print("The series is:")
mySeries=pd.Series(names,index=["A","B","C","D"])
print(mySeries)
mySeries["D"]="Chris"
print("The modified series is:")
print(mySeries)
输出:
The series is:
A 1
B 2.2
C Aditya
D None
dtype: object
The modified series is:
A 1
B 2.2
C Aditya
D Chris
dtype: object
结论
在本文中,我们讨论了如何使用 pandas 模块在 Python 中创建一个系列数据结构。我们还讨论了序列中的索引,如何从序列中删除元素,如何更新序列中的元素,以及如何在序列中插入元素。
想了解更多关于 Python 编程的知识,可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢关于如何用 Python 创建聊天应用程序的文章。
用 Python 解析 JSON 对象
原文:https://www.pythonforbeginners.com/json/parse-json-objects-in-python
概观
在这篇文章中,我们将解释如何用 Python 解析 JSON 对象。
当您想从各种 web 服务访问一个 API
并以 JSON 给出响应时,知道如何解析 JSON 对象是很有用的。
入门指南
你要做的第一件事,就是找到一个 URL 来调用 API。
在我的例子中,我将使用 Twitter API。
从导入程序所需的模块开始。
import json
import urllib2
打开 URL 和屏幕名称。
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=wordpress"
打印出结果
print data
使用 Twitter API 解析数据
这是一个非常简单的程序,只是让你知道它是如何工作的。
#Importing modules
import json
import urllib2
# Open the URL and the screen name
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=wordpress"
# This takes a python object and dumps it to a string which is a JSON representation of that object
data = json.load(urllib2.urlopen(url))
#print the result
print data
如果你有兴趣看另一个如何在 Python 中使用 JSON 的例子,请
看看“IMDB 爬虫”脚本。
要使用 Twitter API,请参阅 Twitter 上的官方文档。
https://dev.twitter.com/docs
用 Python 编码 JSON
原文:https://www.pythonforbeginners.com/json/parsing-json-python
Python 预装了 JSON 编码器和解码器,使得在应用程序中使用 JSON 变得非常简单
对 JSON 进行编码的最简单的方法是使用字典。这个基本字典保存各种数据类型的随机值。
data = {
a: 0,
b: 9.6,
c: "Hello World",
d: {
a: 4
}
}
然后,我们使用 json.dumps()将字典转换成 json 对象。
import json
data = {
a: 0,
b: 9.6,
c: "Hello World",
d: {
a: 4
}
}
json_data = json.dumps(data)
print(json_data)
这将打印出来
{"c": "Hello World", "b": 9.6, "d": {"e": [89, 90]}, "a": 0}
请注意默认情况下键是如何排序的,您必须像这样将 sort_keys=True 参数添加到 json.dumps()中。
import json
data = {
a: 0,
b: 9.6,
c: "Hello World",
d: {
a: 4
}
}
json_data = json.dumps(data, sort_keys=True)
print(json_data)
然后输出排序后的关键字。
{"a": 0, "b": 9.6, "c": "Hello World", "d": {"e": [89, 90]}}
用 Python 解析 JSON
概观
对 HTTP API 的请求通常只是带有一些查询参数的 URL。
API 响应
我们从 API 得到的响应是数据,数据可以有各种格式,最流行的是 XML 和 JSON。
许多 HTTP APIs 支持多种响应格式,因此开发人员可以选择他们更容易解析的格式。
入门指南
首先,让我们创建一个简单的数据结构并放入一些数据。
首先,我们将 json 模块导入到程序中。
import json
# Create a data structure
data = [ { 'Hola':'Hello', 'Hoi':"Hello", 'noun':"hello" } ]
要将数据打印到屏幕上,非常简单:
print 'DATA:', (data)
当我们如上打印数据时,我们将看到以下输出:
DATA: [{'noun': 'hello', 'Hola': 'Hello', 'Hoi': 'Hello'}]
JSON 函数
当您在 Python 中使用 JSON 时,我们可以利用不同函数
Json 转储
json.dumps 函数采用 Python 数据结构,并将其作为 json 字符串返回。
json_encoded = json.dumps(data)
# print to screen
print json_encoded
OUTPUT:
[{"noun": "hello", "Hola": "Hello", "Hoi": "Hello"}]
Json 加载
json.loads()函数接受一个 json 字符串,并将其作为 Python 数据
结构返回。
decoded_data = json.loads(json_encoded)
# print to screen
print decoded_data
OUTPUT:
[{u'noun': u'hello', u'Hola': u'Hello', u'Hoi': u'Hello’}]
Python 中的端口扫描器
原文:https://www.pythonforbeginners.com/code-snippets-source-code/port-scanner-in-python
概观
这篇文章将展示如何用 Python 编写一个小巧易用的端口扫描程序。使用 Python 有很多方法可以做到这一点,我将使用内置的模块套接字来实现。
套接字
Python 中的 socket 模块提供了对 BSD 套接字接口的访问。它包括用于处理实际数据通道的 socket 类,以及用于网络相关任务的函数,例如将服务器名称转换为地址和格式化要通过网络发送的数据。
套接字在互联网上被广泛使用,因为它们是你的计算机所进行的任何一种网络通信的基础。
INET 套接字至少占正在使用的套接字的 99%。您使用的 web 浏览器打开一个套接字并连接到 web 服务器。
任何网络通信都要通过套接字。
有关插座模块的更多信息,请参见官方文档。
套接字函数
在开始我们的示例程序之前,让我们看看我们将要使用的一些套接字函数。
Syntax for creating a socket
sock = socket.socket (socket_family, socket_type)
Creates a stream socket
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
AF_INET
Socket Family (here Address Family version 4 or IPv4)
SOCK_STREAM Socket type TCP connections
SOCK_DGRAM Socket type UDP connections
Translate a host name to IPv4 address format
gethostbyname("host")
Translate a host name to IPv4 address format, extended interface
socket.gethostbyname_ex("host")
Get the fqdn (fully qualified domain name)
socket.getfqdn("8.8.8.8")
Returns the hostname of the machine..
socket.gethostname()
Exception handling
socket.error
使用 Python 套接字制作程序
如何用 Python 制作一个简单的端口扫描程序?
这个小端口扫描程序将尝试连接到您为特定主机定义的每个端口。我们必须做的第一件事是导入套接字库和我们需要的其他库。
打开一个文本编辑器,复制并粘贴下面的代码。
将文件另存为:“portscanner.py”并退出编辑器
#!/usr/bin/env python
import socket
import subprocess
import sys
from datetime import datetime
# Clear the screen
subprocess.call('clear', shell=True)
# Ask for input
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
# Print a nice banner with information on which host we are about to scan
print "-" * 60
print "Please wait, scanning remote host", remoteServerIP
print "-" * 60
# Check what time the scan started
t1 = datetime.now()
# Using the range function to specify ports (here it will scans all ports between 1 and 1024)
# We also put in some error handling for catching errors
try:
for port in range(1,1025):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "Port {}: Open".format(port)
sock.close()
except KeyboardInterrupt:
print "You pressed Ctrl+C"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
except socket.error:
print "Couldn't connect to server"
sys.exit()
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print 'Scanning Completed in: ', total
抽样输出
让我们运行程序,看看输出会是什么样子
$ python portscanner.py
Enter a remote host to scan: www.your_host_example.com
------------------------------------------------------------
Please wait, scanning remote host xxxx.xxxx.xxxx.xxxx
------------------------------------------------------------
Port 21: Open
Port 22: Open
Port 23: Open
Port 80: Open
Port 110: Open
Port 111: Open
Port 143: Open
Port 443: Open
Port 465: Open
Port 587: Open
Port 993: Open
Port 995: Open
Scanning Completed in: 0:06:34.705170
放弃
该程序旨在让个人测试他们自己的设备的弱安全性,如果它被用于任何其他用途,作者将不承担任何责任
Python 中字符串中字符的位置
原文:https://www.pythonforbeginners.com/basics/position-of-a-character-in-a-string-in-python
在 Python 中进行文本分析时,在给定字符串中搜索字符是最常见的任务之一。本文讨论了如何在 python 中找到字符串中字符的位置。
使用 for 循环查找字符串中字符的位置
为了找到一个字符在字符串中的位置,我们将首先使用len()
函数找到字符串的长度。len()
函数将一个字符串作为其输入参数,并返回该字符串的长度。我们将字符串的长度存储在一个变量strLen
中。
获得字符串的长度后,我们将使用range()
函数创建一个包含从 0 到strLen-1
的值的 range 对象。range()
函数将变量strLen
作为其输入参数,并返回一个 range 对象。
接下来,我们将使用一个 python for 循环和 range 对象来遍历字符串字符。当迭代时,我们将检查当前字符是否是我们正在寻找位置的字符。为此,我们将使用索引操作符。如果当前字符是我们正在寻找的字符,我们将打印该字符的位置,并使用 python 中的 break 语句退出循环。否则,我们将移动到下一个字符。
在执行 for 循环之后,如果字符出现在输入字符串中,我们将得到字符的位置,如下所示。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
range_obj=range(strLen)
character="F"
for index in range_obj:
if myStr[index]==character:
print("The character {} is at index {}".format(character,index))
break
输出:
The input string is: Python For Beginners
The character F is at index 7
使用 for 循环查找字符串中出现的所有字符
为了找到字符串中出现的所有字符,我们将从 for 循环中移除 break 语句。由于这个原因,for 循环将检查所有的字符,并打印出它们的位置,如果这个字符是我们正在寻找的。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
range_obj=range(strLen)
character="n"
for index in range_obj:
if myStr[index]==character:
print("The character {} is at index {}".format(character,index))
输出:
The input string is: Python For Beginners
The character n is at index 5
The character n is at index 15
The character n is at index 16
使用 for 循环查找字符串中字符的最右边的索引
为了找到字符最右边的位置,我们需要修改我们的方法。为此,我们将创建一个名为position
的变量来存储字符串中字符的位置,而不是打印位置。在遍历字符串中的字符时,只要找到所需的字符,我们就会不断更新position
变量。
在执行 for 循环之后,我们将获得字符串中最右边的字符的索引。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
range_obj=range(strLen)
character="n"
position=-1
for index in range_obj:
if myStr[index]==character:
position=index
print("The character {} is at rightmost index {}".format(character,position))
输出:
The input string is: Python For Beginners
The character n is at rightmost index 16
上述方法给出了字符从左侧开始的位置。如果想得到字符串中最右边的字符的位置,可以使用下面的方法。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
range_obj=range(strLen)
character="n"
for index in range_obj:
if myStr[strLen-index-1]==character:
print("The character {} is at position {} from right.".format(character,index+1))
break
输出:
The input string is: Python For Beginners
The character n is at position 4 from right.
在这个例子中,我们使用了字符串索引操作符来访问字符串右侧的元素。因此,我们可以用最少的 for 循环执行次数得到任意给定字符的最右边的位置。
使用 While 循环查找字符串中字符的位置
代替 for 循环,您可以使用 while 循环来查找字符串中某个字符的位置。为此,我们将使用以下步骤。
- 首先,我们将定义一个名为
position
的变量,并将其初始化为-1。 - 然后,我们将使用
len()
函数找到字符串的长度。 - 现在,我们将使用 while 来遍历字符串中的字符。如果位置变量变得大于或等于字符串的长度,我们将定义退出条件。
- 在 while 循环中,我们将首先递增
position
变量。接下来,我们将检查当前位置的字符是否是我们要寻找的字符。如果是,我们将打印字符的位置,并使用 break 语句退出 while 循环。否则,我们将移动到下一个字符。
在执行 while 循环之后,我们将获得字符串中第一个出现的字符的索引。您可以在下面的代码中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=-1
while position<strLen-1:
if myStr[position+1]==character:
print("The character {} is at position {}.".format(character,position+1))
break
position+=1
输出:
The input string is: Python For Beginners
The character n is at position 5.
使用 While 循环查找字符串中出现的所有字符
如果要查找字符串中出现的所有字符,可以从 while 循环中删除 break 语句。此后,程序将打印给定字符串中字符的所有位置,如下所示。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=-1
while position<strLen-1:
if myStr[position+1]==character:
print("The character {} is at position {}.".format(character,position+1))
position+=1
输出:
The input string is: Python For Beginners
The character n is at position 5.
The character n is at position 15.
The character n is at position 16.
使用 While 循环查找字符串中字符的最右边的索引
为了使用 Python 中的 while 循环找到字符最右边的位置,我们将创建一个名为rposition
的变量来存储字符串中字符的位置,而不是打印位置。当使用 While 循环遍历字符串的字符时,每当我们找到所需的字符时,我们将不断更新rposition
变量。
在 while 循环执行之后,我们将获得字符串中最右边的字符的位置。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=-1
rposition=0
while position<strLen-1:
if myStr[position+1]==character:
rposition=position+1
position+=1
print("The character {} is at rightmost position {}.".format(character,rposition))
输出:
The input string is: Python For Beginners
The character n is at rightmost position 16.
上述方法给出了字符从左侧开始的位置。如果想得到字符串中最右边的字符的位置,可以使用下面的方法。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=0
while position<strLen-1:
if myStr[strLen-position-1]==character:
print("The character {} is at position {} from right.".format(character,position+1))
break
position+=1
输出:
The input string is: Python For Beginners
The character n is at position 4 from right.
使用 Find()方法查找字符在字符串中的位置
要查找字符串中某个字符的位置,也可以使用find()
方法。在字符串上调用find()
方法时,它将一个字符作为输入参数。执行后,它返回字符串中第一个出现的字符的位置。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=myStr.find(character)
print("The character {} is at position {}.".format(character,position))
输出:
The input string is: Python For Beginners
The character n is at position 5.
建议阅读:用 Python 创建聊天应用
使用 Index()方法查找字符串中某个字符的索引
index()
方法用于查找字符串中某个字符的索引。在字符串上调用index()
方法时,它将一个字符作为输入参数。执行后,它返回字符串中第一个出现的字符的位置。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=myStr.index(character)
print("The character {} is at index {}.".format(character,position))
输出:
The input string is: Python For Beginners
The character n is at index 5.
使用 rfind()方法在 Python 中查找字符串的最右边的索引
要找到 python 字符串中某个字符的最右边位置,也可以使用rfind()
方法。除了返回字符串中输入字符最右边的位置之外,rfind()
方法的工作方式与find()
方法类似。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
strLen=len(myStr)
character="n"
position=myStr.rfind(character)
print("The character {} is at rightmost position {} .".format(character,position))
输出:
The input string is: Python For Beginners
The character n is at rightmost position 16 .
结论
在本文中,我们讨论了在 Python 中查找字符串中字符位置的不同方法。要了解关于这个主题的更多信息,您可以阅读这篇关于如何在字符串中找到一个子字符串的所有出现的文章。
您可能也会喜欢这篇关于 python simplehttpserver 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中的后序树遍历算法
原文:https://www.pythonforbeginners.com/data-structures/postorder-tree-traversal-algorithm-in-python
二叉树在表示层次数据方面非常有用。在本文中,我们将讨论如何使用后序树遍历打印二叉树中的所有元素。我们还将在 python 中实现后序树遍历算法。
后序树遍历算法是什么?
后序遍历算法是一种深度优先遍历算法。这里,我们从一个根节点开始,遍历树的一个分支,直到到达分支的末端。之后,我们转移到下一个分支。这个过程一直持续到树中的所有节点都被打印出来。
后序树遍历算法的名字来源于树的节点被打印的顺序。在这个算法中,我们首先打印节点的左子树,然后打印当前节点的右子树。最后,我们打印当前节点。这个过程本质上是递归的。这里,仅当当前节点的左子树和右子树中的所有节点都已经被打印时,才打印该节点。
让我们使用下图中给出的二叉树来理解这个过程。
Binary Tree
让我们使用后序遍历算法打印上述二叉树中的所有节点。
- 我们将从节点 50 开始。在打印 50 之前,我们必须打印它的左子树和右子树。所以,我们将移动到 20。
- 在打印 20 之前,我们必须打印它的左子树和右子树。所以,我们将搬到 11 楼。
- 由于 11 没有孩子,我们将打印 11。此后,我们将移动到前一个节点,即 20。
- 由于 20 的左侧子树已经打印,我们将移动到 20 的右侧子树,即 22。
- 由于 22 没有孩子,我们将打印 22。此后,我们将移动到前一个节点,即 20。
- 因为已经打印了 20 的左子树和右子树。我们将打印 20,并将移动到其父节点,即 50。
- 此时,左侧 50 个子树已经被打印。因此,将打印其右边的子树。我们将搬到 53 楼。
- 在打印 53 之前,我们必须打印它的左子树和右子树。所以,我们要搬到 52 楼。
- 由于 52 没有子节点,我们将打印 52。此后,我们将移动到前一个节点,即 53。
- 因为已经打印了 53 的左侧子树,所以我们将移动到 53 的右侧子树,即 78。
- 由于 78 没有子节点,我们将打印 78。此后,我们将移动到前一个节点,即 53。
- 由于 53 的左子树和右子树都已打印,我们将打印 53,并将移动到其父节点,即 50。
- 此时,50 的左子树和右子树都已经打印出来了,所以,我们将打印 50。
- 由于树中的所有节点都已经被打印,我们将终止这个算法。
您可以看到,我们按照 11、22、20、52、78、53、50 的顺序打印了这些值。现在让我们为后序树遍历算法制定一个算法。
后序树遍历算法
由于您对整个过程有一个总体的了解,我们可以将后序树遍历的算法公式化如下。
- 从根节点开始。
- 如果根为空,则返回。
- 递归遍历左边的子树。
- 递归遍历右边的子树。
- 打印根节点。
- 停下来。
Python 中后序树遍历的实现
我们已经理解了后序树遍历的算法及其工作原理,让我们实现该算法,并对上图中给出的二叉树执行该算法。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def postorder(root):
# if root is None,return
if root is None:
return
# traverse left subtree
postorder(root.leftChild)
# traverse right subtree
postorder(root.rightChild)
# print the current node
print(root.data, end=" ,")
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# if newValue is less than value of data in root, add it to left subtree and proceed recursively
if newValue < root.data:
root.leftChild = insert(root.leftChild, newValue)
else:
# if newValue is greater than value of data in root, add it to right subtree and proceed recursively
root.rightChild = insert(root.rightChild, newValue)
return root
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Postorder traversal of the binary tree is:")
postorder(root)
输出:
Postorder traversal of the binary tree is:
11 ,22 ,20 ,52 ,78 ,53 ,50 ,
结论
在本文中,我们讨论并实现了后序树遍历算法。要了解更多关于其他树遍历算法的内容,可以阅读这篇关于 Inorder tree 遍历算法或 level order tree 遍历算法in python 的文章。
Python 中的前序树遍历算法
原文:https://www.pythonforbeginners.com/data-structures/preorder-tree-traversal-algorithm-in-python
二叉树在表示层次数据方面非常有用。在本文中,我们将讨论如何用 python 打印一棵二叉树中的所有元素。为此,我们将使用前序树遍历算法。我们还将在 python 中实现前序树遍历。
什么是前序树遍历?
前序树遍历是一种深度优先遍历算法。这里,我们从一个根节点开始,遍历树的一个分支,直到到达分支的末端。之后,我们转移到下一个分支。这个过程一直持续到树中的所有节点都被打印出来。
前序树遍历算法的名字来源于树的节点被打印的顺序。在这个算法中,我们首先打印一个节点。之后,我们打印节点的左边的子节点。最后,我们打印出节点的正确子节点。这个过程本质上是递归的。这里,只有当当前节点的左子树中的所有节点和当前节点本身都已经被打印时,才打印节点的右子节点。
让我们使用下图中给出的二叉树来理解这个过程。
Binary Tree
让我们使用前序遍历打印上述二叉树中的所有节点。
- 首先,我们将从根节点开始,打印它的值,即 50。
- 之后,我们必须打印 50 的左孩子。因此,我们将打印 20 个。
- 打印完 20,还要打印 20 的左子。因此,我们将打印 11。
- 11 没有孩子。因此,我们将移动到节点 20 并打印它的右边的子节点,即我们将打印 22。
- 22 没有孩子,所以我们将搬到 20。所有 20 岁的孩子都被打印出来了。所以,我们将移动到 50。在 50 处,我们将打印它的右子节点,因为它的左子树中的所有节点都已经被打印了。因此,我们将打印 53。
- 打印完 53,还要打印 53 的左子。因此,我们将打印 52。
- 52 没有孩子。因此,我们将移动到节点 53 并打印它的右子节点,即我们将打印 78。
- 此时,我们已经打印了二叉树中的所有节点。因此,我们将终止这一进程。
您可以看到,我们按照 50、20、11、22、53、52、78 的顺序打印了这些值。现在让我们为前序树遍历制定一个算法。
前序树遍历算法
由于您对整个过程有一个总体的了解,我们可以将前序树遍历的算法公式化如下。
- 从根节点开始。
- 如果根目录为空,转到 6。
- 打印根节点。
- 递归遍历左边的子树。
- 递归遍历右边的子树。
- 停下来。
Python 中前序树遍历的实现
我们已经讨论了前序树遍历的算法及其工作原理,让我们实现该算法,并对上图中给出的二叉树执行该算法。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def preorder(root):
# if root is None,return
if root is None:
return
# print the current node
print(root.data, end=" ,")
# traverse left subtree
preorder(root.leftChild)
# traverse right subtree
preorder(root.rightChild)
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# if newValue is less than value of data in root, add it to left subtree and proceed recursively
if newValue < root.data:
root.leftChild = insert(root.leftChild, newValue)
else:
# if newValue is greater than value of data in root, add it to right subtree and proceed recursively
root.rightChild = insert(root.rightChild, newValue)
return root
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Preorder traversal of the binary tree is:")
preorder(root)
输出:
Preorder traversal of the binary tree is:
50 ,20 ,11 ,22 ,53 ,52 ,78 ,
您可以观察到,代码给出的输出与我们在讨论该算法时得到的输出相同。
结论
在本文中,我们讨论并实现了 Python 中的前序树遍历算法。要了解其他树遍历算法的更多信息,可以阅读 python 中的顺序树遍历和 Python 中的层次顺序树遍历中关于的文章。
Python 中不带换行符的打印
原文:https://www.pythonforbeginners.com/basics/print-without-newline-in-python
在编程时,我们使用print()
函数将一个字符串或一个值打印到标准输出。通常,每个print()
函数在新的一行打印一个值。然而,我们可以改变函数的这种行为。在本文中,我们将看到如何在 python 中不使用换行符进行打印。
Python 中如何不换行打印?
print()
函数接受各种输入参数以及要打印的值。通常,当我们不向print()
函数传递任何额外的参数时,它会在每次调用该函数时在一个新行上打印值。您可以在下面的示例中观察到这一点。
print("This is the first line.")
print("This is the second line.")
print("This is the third line.")
print("This is the fourth line.")
输出:
This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
我们可以通过使用参数“end
”来改变print()
函数的这种行为。参数“end
”用于指定字符。print()
函数在打印传递给它的值后进行打印。参数“end
”的默认值为“\n
”,即换行符。这就是为什么print()
函数在打印值后打印一个换行符。因此,下一个print()
语句总是在新的一行打印值。
您可以传递任何字符作为参数“end
”的输入参数。print()
函数在执行时,总是在打印实际值后打印作为输入参数传递的字符。例如,你可以通过句号“.”字符给参数“end
”作为输入参数。这将使print()
功能在打印实际输入值后打印一个句点。您可以在下面的示例中观察到这一点。
print("This is the first line.", end=".")
print("This is the second line.", end=".")
print("This is the third line.", end=".")
print("This is the fourth line.", end=".")
输出:
This is the first line..This is the second line..This is the third line..This is the fourth line..
要在每个 print 语句执行后打印一个逗号,可以将“,”作为输入参数传递给print()
函数,如下所示。
print("This is the first line.", end=",")
print("This is the second line.", end=",")
print("This is the third line.", end=",")
print("This is the fourth line.", end=",")
输出:
This is the first line.,This is the second line.,This is the third line.,This is the fourth line.,
同样,您可以传递连字符、&、*、$、@、!、圆括号、方括号或任何其他字符添加到参数"end
"中。您甚至可以将字母和数字作为输入参数传递给print()
函数。在打印实际值之后,print()
函数将简单地打印传递给参数“end
的字符,而不打印到换行符。
结论
在本文中,我们讨论了如何在 python 中不使用换行符进行打印。通过使用 python 中的字符串格式,还可以在打印时修改字符串的外观。要了解更多关于 python 中字符串的知识,你可以阅读这篇关于字符串连接的文章。
Python 2 与 Python 3 的比较及示例
原文:https://www.pythonforbeginners.com/development/python-2-vs-python-3-examples
Python 是一种高度通用的解释型高级通用编程语言。它由吉多·范·罗苏姆创作,于 1991 年首次发行。Python 的设计理念强调代码可读性和易用性。从那以后,Python 越来越受欢迎,是脚本编写和快速应用程序开发的绝佳选择。
许多遗留应用程序仍然是用 Python 2 编写的。面临迁移到 Python 3 的公司需要了解语法和行为上的差异。本文的目的是概述 Python 2 和 Python 3 之间的区别。通过示例,您将看到函数在一个版本中看起来语法相同,但在另一个版本中行为完全不同。
最常用的 Python 版本
Python 的最新版本是 2018 年发布的 3.7。下一个版本 3.8 目前正在开发中,将于 2024 年发布。虽然 Python 2.7 还在广泛使用。Python 3 的采用正在快速增长。2016 年,71.9%的项目使用 Python 2.7,但到 2017 年,已经下降到 63.7%。
我应该使用什么版本?
根据你的需求和你想做的事情,选择对你最有帮助的版本。如果你能用 Python 3.x 做你想做的事情,那就太好了!但是,也有一些缺点,例如:
- 稍微差一点的库支持
- 一些当前的 Linux 发行版和 MAC 仍然默认使用 2.x
只要 Python 3.x 安装在用户的计算机上(在大多数情况下,这是因为大多数阅读本文的人正在为自己或在他们控制的环境中开发一些东西),并且您正在编写的东西不需要 Python 2.x 模块,那么它就是一个极好的选择。此外,大多数 Linux 发行版已经安装了 Python 3.x,并且几乎所有的最终用户都可以使用它。一个警告可能是,如果 Python 3 的 Red Hat Enterprise Linux(通过版本 7)确实存在于 EPEL 库中,但是一些用户可能不被允许从附加位置或不安全的位置安装任何东西。此外,一些发行版正在逐步淘汰 Python 2 作为以前的默认安装。
讲师应该向新的程序员介绍 Python 3,但是讨论 Python 2 中的不同之处。
不要在 Python 2 中开始任何新的开发,因为从 2020 年 1 月起,Python 2 将停止使用,这意味着所有官方支持都将停止。
Python 2 和 3 有什么区别?
主要区别在于,有些东西需要从不同的地方导入,以便处理它们在 Python 2 和 Python 3 中有不同名称的事实。因此,six compatibility package 是在单一代码库中支持 Python 2 和 Python 3 的关键工具。
我们将在本文的每一节中讨论主要的区别,并提供 Python 2 和 Python 3 中控制台截图的例子。
库:Python 2 与 Python 3
从库的角度来看,Python 2 和 Python 3 中的库有很大的不同。许多为 Python 2 开发的库在 Python 3 中不兼容。Python 3 中使用的库的开发者具有良好的标准,并且增强了机器学习和深度学习库。
Python 2 和 3 中的整数除法
整数除法是两个数减去小数部分的除法。在 Python 2 中,您可以确切地了解定义整数除法的目的。
例 1。Python 2 中的整数除法。
在下面的控制台截图中,您可以看到两个整数的除法。Python 2 中的结果也是整数。缺少小数部分。
例 2。Python 3 中的整数除法。
在下面的控制台截图中,你可以看到 Python 3 中两个整数的除法。结果是一个浮点数,其中包含 Python 2 中缺少的小数部分。
如果 Python 2 中需要小数部分,那么可以指定一个被除的整数作为浮点数。这样,它强制结果为浮点数。
Python 2 和 3 的打印语句语法
在 Python 2 中,print 是一个带有多个参数的语句。它打印的参数之间有一个空格。在 Python 3 中,print 是一个接受多个参数的函数。
例 3。Python 2 中的打印语句
在本例中,我们使用带有三个参数的 print 语句。请注意,Python 2 打印了由空格分隔的三个参数。接下来,我们使用 print 语句,用圆括号将三个参数括起来。结果是一个由三个元素组成的元组。
例 4。Python 3 中的打印函数。
在这个例子中,我们使用带有三个参数的 print 函数,得到的结果与使用 Python 2 的例子 3 中的结果相同。然而,当我们想要打印元组时,我们必须用另一组圆括号将元组括起来。
为了在 Python 2 中获得与 Python 3 相同的结果,我们可以使用 future 指令来指导编译器使用未来版本中可用的特性。
例 5。Python 2 中的未来指令。
Python 2 和 Python 3 中的 Unicode 支持
在 Python 2 中,当您打开一个文本文件时,open()函数会返回一个 ASCII 文本字符串。在 Python 3 中,同一个函数 open()返回一个 unicode 字符串。Unicode 字符串比 ASCII 字符串更通用。说到存储,如果想在 Python 2 中将 ASCII 字符串存储为 Unicode,就必须加上一个“u”。
例 6。Python 2 中的字符串
例 7。Python 3 中的字符串。
在 Python 2 中,有两种不同的对象可以用来表示字符串。这些是“字符串”和“unicode”。“str”的实例是字节表示,而对于 unicode,是 16 或 32 位整数。Unicode 字符串可以用 encode()函数转换成字节字符串。
在 Python 3 中,也有两种不同的对象可以用来表示字符串。这些是“字符串”和“字节”。“str”对应于 Python 2 中的“unicode”类型。您可以将一个变量声明为“str ”,并在其中存储一个字符串,而不用在它前面加上“u ”,因为它现在是默认的。“Bytes”对应于 Python 2 中的“str”类型。这是一种由 8 位整数序列表示的二进制序列化格式,非常适合通过互联网发送或存储在文件系统中。
处理 Python 2 和 Python 3 时出错
Python 中的错误处理包括引发异常和提供异常处理程序。Python 2 和 Python 3 的区别主要在语法上。我们来看几个例子。
例 8。在 Python 2 中引发错误。
在下面的控制台截图中,我们尝试在两种格式下都显示错误,并且成功了。
例 9。在 Python 3 中引发错误。
在下面的控制台截图中,在 Python 3 中引发错误不像在 Python 2 中那样有效。
对于异常处理程序,Python 3 中的语法略有变化。
例 10。Python 2 中的 Try 和 Exception 块。
在下面的控制台截图中,我们指定了一个带有异常处理程序的 try 块。我们故意在“try”中指定一个未定义的名称来导致错误。
例 11。Python 3 中的 Try 和 Exception 块。
在下面的控制台截图中,我们指定了与 Python 2 中的上一个示例相同的代码。请注意 Python 3 中的新语法,要求我们使用“as”这个词。
比较不可排序类型
在 Python 2 中,可以比较无序的类型,比如带有字符串的列表。
例 12。将列表与字符串进行比较。
例 13。在 Python 3 中比较列表和字符串。
Python 3 中的新特性,如果你试图比较一个列表和一个字符串,会引发一个类型错误。
Python 2 和 Python 3 中的 XRange
在 Python 2 中,有 range()函数和 xrange()函数。range()函数将返回一个数字列表,而 xrange()函数将返回一个对象。
在 Python 3 中,只有 range()函数,没有 xrange()函数。之所以没有 xrange()函数,是因为 range()函数的行为类似于 Python 2 中的 xrange()函数。换句话说,range()函数返回 range 对象。
实施例 14。Python 2 中的 Range()和 XRange()函数。
在下面的控制台截图中,我们看到 range()函数返回一个包含 5 个元素的列表,因为我们传递了“5”作为参数。当我们使用 xrange()时,我们得到的是一个对象。
实施例 15。Python 3 中的 Range()函数。
从下面的控制台截图可以看出,输入 range()函数并以' 5 '作为参数会导致返回一个对象。然而,当我们尝试使用 xrange()函数时,我们看到 Python 3 不喜欢它,因为它是未定义的。
在 Python 2 中,有许多返回列表的函数。在 Python 3 中,做了一个改变,返回可迭代对象而不是列表。这包括以下功能:
- zip()
- 地图()
- 过滤器()
- 字典的。key()方法
- 字典的。values()方法
- 字典的。items()方法
Python 2 与 3 中的未来模块
如果您计划让 Python 3 支持您的 Python 2 代码,那么您可能希望添加 future 模块。例如,整数除法已经从 Python 2 更改为 3,但是如果您希望您的 Python 2 代码的行为像 Python 3 一样,您所要做的就是添加这一行:
“从 __ 未来 _ _ 进口部门”
现在,在 Python 2 代码中,将两个整数相除将产生一个浮点数。
实施例 16。从 future 模块导入。
正如你在下面看到的,当我们除以 2 / 3,我们得到 0,这是整数类型。但是在我们从 future 模块导入除法之后,2 / 3 返回了浮点数类型。
您还可以指定其他事情来简化未来的迁移。它们包括:
- 发电机
- 分开
- 绝对 _ 进口
- With _ 语句
- 打印 _ 功能
- Unicode _ 文字
Python all()函数
原文:https://www.pythonforbeginners.com/basics/python-all-function
在 python 中,我们通常使用比较运算符和逻辑运算符来检查不同数量元素的条件。如果您必须检查元素列表中的条件,该怎么办?在本文中,我们将讨论 python 中的all()
函数。我们还将看到如何对不同的可迭代对象使用all()
函数。
Python 中的all()
函数是什么?
all()
函数用于检查一个 iterable 对象中的所有元素是否都等于True
。all()
函数将列表、元组、集合、字典或字符串等可迭代对象作为其输入参数。执行后,如果 iterable 的所有元素的值都是True
,它将返回True
。否则返回False
。您可以在下面的示例中观察到这一点。
myList1 = [1, 2, 3, 4]
myList2 = [1, True, False]
myList3 = []
print("The list is:", myList1)
output = all(myList1)
print("All the elements of the list evaluate to True:", output)
print("The list is:", myList2)
output = all(myList2)
print("All the elements of the list evaluate to True:", output)
print("The list is:", myList3)
output = all(myList3)
print("All the elements of the list evaluate to True:", output)
输出:
The list is: [1, 2, 3, 4]
All the [elements of the list](https://www.pythonforbeginners.com/basics/find-the-index-of-an-element-in-a-list) evaluate to True: True
The list is: [1, True, False]
All the elements of the list evaluate to True: False
The list is: []
All the [elements of the list](https://www.pythonforbeginners.com/basics/find-the-index-of-an-element-in-a-list) evaluate to True: True
你可以把all()
函数的工作理解为and
操作符的一个应用。对于具有元素element1, element2, element3,.... elementN
的可迭代对象,使用all()
函数相当于执行语句 element1 AND element2 AND element3 AND ….., AND elementN
。
带有 iterable 对象的 all()函数
当我们将一个列表作为输入参数传递给 all()函数时,如果列表的所有元素的值都为 True,那么它将返回 True。
myList1 = [1, 2, 3, 4]
myList2 = [1, True, False]
myList3 = []
print("The list is:", myList1)
output = all(myList1)
print("All the elements of the list evaluate to True:", output)
print("The list is:", myList2)
output = all(myList2)
print("All the elements of the list evaluate to True:", output)
print("The list is:", myList3)
output = all(myList3)
print("All the elements of the list evaluate to True:", output)
输出:
The list is: [1, 2, 3, 4]
All the elements of the list evaluate to True: True
The list is: [1, True, False]
All the elements of the list evaluate to True: False
The list is: []
All the elements of the list evaluate to True: True
当我们将一个空列表传递给all()
函数时,它返回True
。但是,如果列表中有一个元素的值为False
,那么all()
函数将返回False
。
当我们将任何字符串作为输入参数传递给all()
函数时,它返回True
。
myStr1 = "PythonForBeginners"
myStr2 = ""
print("The string is:", myStr1)
output = all(myStr1)
print("The output is:", output)
print("The string is:", myStr2)
output = all(myStr2)
print("The output is:", output)
输出:
The string is: PythonForBeginners
The output is: True
The string is:
The output is: True
对于空字符串,all()
函数返回True
。
类似于列表,当我们将一个集合作为输入参数传递给all()
函数时,如果该集合的所有元素的值都为True
,它将返回True
。
mySet1 = {1, 2, 3, 4}
mySet2 = {1, 2, True, False}
mySet3 = set()
print("The Set is:", mySet1)
output = all(mySet1)
print("All the elements of the set evaluate to True:", output)
print("The Set is:", mySet2)
output = all(mySet2)
print("All the elements of the set evaluate to True:", output)
print("The Set is:", mySet3)
output = all(mySet3)
print("All the elements of the set evaluate to True:", output)
输出:
The Set is: {1, 2, 3, 4}
All the elements of the set evaluate to True: True
The Set is: {False, 1, 2}
All the elements of the set evaluate to True: False
The Set is: set()
All the elements of the set evaluate to True: True
当我们将一个空集传递给all()
函数时,它返回True
。
Python 中带字典的 all()函数
当我们将一个字典作为输入参数传递给all()
函数时,如果 python 字典的所有键都评估为True
,它将返回True
。否则返回False
。
myDict1 = {1: 1, 2: 2, 3: 3, True: 4}
myDict2 = {False: 1, 1: 2, True: False}
myDict3 = {}
print("The Dictionary is:", myDict1)
output = all(myDict1)
print("All the keys of the dictionary evaluate to True:", output)
print("The Dictionary is:", myDict2)
output = all(myDict2)
print("All the keys of the dictionary evaluate to True:", output)
print("The Dictionary is:", myDict3)
output = all(myDict3)
print("All the keys of the dictionary evaluate to True:", output)
输出:
The Dictionary is: {1: 4, 2: 2, 3: 3}
All the keys of the dictionary evaluate to True: True
The Dictionary is: {False: 1, 1: False}
All the keys of the dictionary evaluate to True: False
The Dictionary is: {}
All the keys of the dictionary evaluate to True: True
当我们将一个空字典传递给all()
函数时,它返回 True。
结论
在本文中,我们讨论了 python 中的 all()函数。我们还对不同的可迭代对象使用了all()
函数,并观察了函数的输出。要了解更多关于 python 编程的知识,你可以在列表理解上阅读这篇文章。
Python 和 MySQL 与 MySQLdb
原文:https://www.pythonforbeginners.com/modules-in-python/python-and-mysql-with-mysqldb
上周,我在寻找一个 Python 模块,可以用来与 MySQL 数据库服务器进行交互。MySQLdb 正在这么做。
“MySQLdb 是一个围绕 _mysql 的瘦 Python 包装器,这使得它与 Python DB API 接口(版本 2)兼容。实际上,为了提高效率,相当一部分实现 API 的代码都在 mysql 中。”
要安装和使用它,只需运行:sudo apt-get install python-mysqldb
完成后,您可以开始在脚本中导入 MySQLdb 模块。
我在亚历克斯·哈维的网站上找到了这段代码
# Make the connection
connection = MySQLdb.connect(host='localhost',user='alex',passwd='secret',db='myDB')
cursor = connection.cursor()
# Lists the tables in demo
sql = "SHOW TABLES;"
# Execute the SQL query and get the response
cursor.execute(sql)
response = cursor.fetchall()
# Loop through the response and print table names
for row in response:
print row[0]
关于如何在 Python 中使用 MySQLdb 的更多例子,请看一下Zetcode.com。
Python any()函数
原文:https://www.pythonforbeginners.com/basics/python-any-function
在 python 中,我们通常使用比较运算符和逻辑运算符来检查不同数量元素的条件。如果您必须检查元素列表中的条件,该怎么办?在本文中,我们将讨论 python 中的 any()函数。我们还将看到如何对不同的可迭代对象使用any()
函数。
Python 中的 any()是什么?
any()函数用于检查在一个 iterable 对象中是否存在一个元素,该元素的值是否为 True。any()
函数将列表、元组、集合、字典或字符串等可迭代对象作为其输入参数。执行后,如果 iterable 中至少有一个元素的值为True
,它将返回True
。否则返回False
。您可以在下面的示例中观察到这一点。
myList1 = [1, 2, 3, 4]
myList2 = [False, False, False]
myList3 = []
print("The list is:", myList1)
output = any(myList1)
print("List contains one or more elements that evaluate to True:", output)
print("The list is:", myList2)
output = any(myList2)
print("List contains one or more elements that evaluate to True:", output)
print("The list is:", myList3)
output = any(myList3)
print("List contains one or more elements that evaluate to True:", output)
输出:
The list is: [1, 2, 3, 4]
List contains one or more elements that evaluate to True: True
The list is: [False, False, False]
List contains one or more elements that evaluate to True: False
The list is: []
List contains one or more elements that evaluate to True: False
你可以把any()
函数的工作理解为or
操作符的一个应用。对于具有元素element1, element2, element3,.... elementN
的可迭代对象,使用any()
相当于执行语句 element1 OR element2 OR element3 OR ….., OR elementN
。
Python 中带有可迭代对象的 any()函数
当我们将一个列表作为输入参数传递给 any()函数时,如果列表的元素中至少有一个元素的值为 True,它将返回 True。
myList1 = [1, 2, 3, 4]
myList2 = [False, False, False]
myList3 = []
print("The list is:", myList1)
output = any(myList1)
print("List contains one or more elements that evaluate to True:", output)
print("The list is:", myList2)
output = any(myList2)
print("List contains one or more elements that evaluate to True:", output)
print("The list is:", myList3)
output = any(myList3)
print("List contains one or more elements that evaluate to True:", output)
输出:
The list is: [1, 2, 3, 4]
List contains one or more elements that evaluate to True: True
The list is: [False, False, False]
List contains one or more elements that evaluate to True: False
The list is: []
List contains one or more elements that evaluate to True: False
当我们将一个空列表传递给any()
函数时,它返回 False。
当我们将任何非空字符串作为输入参数传递给any()
函数时,它返回True
。
myStr1="PythonForBeginners"
myStr2=""
print("The string is:", myStr1)
output = any(myStr1)
print("The string contains one or more elements:", output)
print("The string is:", myStr2)
output = any(myStr2)
print("The string contains one or more elements:", output)
输出:
The string is: PythonForBeginners
The string contains one or more elements: True
The string is:
The string contains one or more elements: False
对于空字符串,any()
函数返回False
。
与列表类似,当我们将一个集合作为输入参数传递给 any()函数时,如果集合的元素中至少有一个元素的值为 True,则返回 True。
mySet1 = {1, 2, 3, 4}
mySet2 = {False}
mySet3 = set()
print("The Set is:", mySet1)
output = any(mySet1)
print("Set contains one or more elements that evaluate to True:", output)
print("The Set is:", mySet2)
output = any(mySet2)
print("Set contains one or more elements that evaluate to True:", output)
print("The Set is:", mySet3)
output = any(mySet3)
print("Set contains one or more elements that evaluate to True:", output)
输出:
The Set is: {1, 2, 3, 4}
Set contains one or more elements that evaluate to True: True
The Set is: {False}
Set contains one or more elements that evaluate to True: False
The Set is: set()
Set contains one or more elements that evaluate to True: False
当我们将一个空集传递给any()
函数时,它返回False
。
Python 中带字典的 any()函数
当我们将字典作为输入参数传递给any()
函数时,如果 python 字典中至少有一个键的值为True
,它将返回True
。否则返回False
。
myDict1 = {1: 1, 2: 2, 3: 3, 4: 4}
myDict2 = {False: 1}
myDict3 = {}
print("The Dictionary is:", myDict1)
output = any(myDict1)
print("Dictionary contains one or more keys that evaluate to True:", output)
print("The Dictionary is:", myDict2)
output = any(myDict2)
print("Dictionary contains one or more keys that evaluate to True:", output)
print("The Dictionary is:", myDict3)
output = any(myDict3)
print("Dictionary contains one or more keys that evaluate to True:", output)
输出:
The Dictionary is: {1: 1, 2: 2, 3: 3, 4: 4}
Dictionary contains one or more keys that evaluate to True: True
The Dictionary is: {False: 1}
Dictionary contains one or more keys that evaluate to True: False
The Dictionary is: {}
Dictionary contains one or more keys that evaluate to True: False
当我们将一个空字典传递给any()
函数时,它返回False
。
结论
在本文中,我们讨论了 python 中的 any()函数。我们还对不同的可迭代对象使用了any()
函数,并观察了函数的输出。要了解更多关于 python 编程的知识,你可以在列表理解上阅读这篇文章。
Python API 和 JSON
原文:https://www.pythonforbeginners.com/json/python-api-and-json
什么是 API?
应用编程接口(API)是一种协议,旨在被软件组件用作相互通信的接口。它基本上是一组用于访问基于 Web 的软件应用程序或 Web 工具的编程指令和标准。一家软件公司(如亚马逊、谷歌等)向公众发布其 API,以便其他软件开发商可以设计由其服务驱动的产品。关于 API 更详细的解释,请阅读来自 howstuffworks.com 的这篇优秀文章。
使用 JSON 与 API 交互
重要的是要知道 API 是软件到软件的接口,而不是用户接口。有了 API,应用程序可以在没有任何用户知识或干预的情况下相互交流。当我们想要与 Python 中的 API 交互时(比如访问 web 服务),我们以一种叫做 JSON 的形式得到响应。为了与 json 交互,我们可以使用 JSON 和 simplejson 模块。JSON (JavaScript Object Notation)是一种紧凑的、基于文本的计算机数据交换格式,曾经像字典一样加载到 Python 中。JSON 数据结构直接映射到 Python 数据类型,这使得它成为直接访问数据的强大工具,而无需编写任何 XML 解析代码。
我该怎么做?
让我们展示如何通过使用 Twittes API 来实现这一点。你要做的第一件事,就是找到一个 URL 来调用 API。下一步是导入我们需要的模块。
import json
import urllib2
# open the url and the screen name
# (The screen name is the screen name of the user for whom to return results for)
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=python"
# this takes a python object and dumps it to a string which is a JSON
# representation of that object
data = json.load(urllib2.urlopen(url))
# print the result
print data
更多示例
来源
BeautifulSoup 简介
原文:https://www.pythonforbeginners.com/beautifulsoup/python-beautifulsoup-basic
什么是 BeautifulSoup?
BeautifulSoup is a Python library from [www.crummy.com](http://www.crummy.com/software/BeautifulSoup/ "crummy")
它能做什么
On their website they write "Beautiful Soup parses anything you give it, and does the tree traversal stuff for you.
**You can tell it to:**
"Find all the links"
"Find all the links of class externalLink"
"Find all the links whose urls match "foo.com"
"Find the table heading that's got bold text, then give me that text.""
美丽的例子
In this example, we will try and find a link (a tag) in a webpage.
Before we start, we have to import two modules. (BeutifulSoup and urllib2).
Urlib2 is used to open the URL we want.
We will use the soup.findAll method to search through the soup object to match fortext and html tags within the page.
from BeautifulSoup import BeautifulSoup
import urllib2
url = urllib2.urlopen("http://www.python.org")
content = url.read()
soup = BeautifulSoup(content)
links = soup.findAll("a")
输出
That will print out all the elements in python.org with an "a" tag.
(The "a" tag defines a hyperlink, which is used to link from one page to another.)
美丽组图示例 2
To make it a bit more useful, we can specify the URL's we want to return.
from BeautifulSoup import BeautifulSoup
import urllib2
import re
url = urllib2.urlopen("http://www.python.org")
content = url.read()
soup = BeautifulSoup(content)
for a in soup.findAll('a',href=True):
if re.findall('python', a['href']):
print "Found the URL:", a['href']
进一步阅读
I recommend that you head over to [http://www.crummy.com](http://www.crummy.com/software/BeautifulSoup/ "Crummy") to read more about what you can do with this awesome module.
在 Python 中使用 urllib2 和 BeautifulSoup
原文:https://www.pythonforbeginners.com/beautifulsoup/python-beautifulsoup
在昨天的帖子里,我给了 BeautifulSoup 一个介绍。
因为 BeautifulSoup 没有为您获取网页,所以您必须使用 urllib2 模块来完成这项工作。
美丽的例子
请查看代码中的注释,看看它做了什么
#import the library used to query a website
import urllib2
#specify the url you want to query
url = "http://www.python.org"
#Query the website and return the html to the variable 'page'
page = urllib2.urlopen(url)
#import the Beautiful soup functions to parse the data returned from the website
from BeautifulSoup import BeautifulSoup
#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page)
#to print the soup.head is the head tag and soup.head.title is the title tag
print soup.head
print soup.head.title
#to print the length of the page, use the len function
print len(page)
#create a new variable to store the data you want to find.
tags = soup.findAll('a')
#to print all the links
print tags
#to get all titles and print the contents of each title
titles = soup.findAll('span', attrs = { 'class' : 'titletext' })
for title in allTitles:
print title.contents
在接下来的文章中,我会写更多关于这个令人敬畏的模块。
Python 按位运算符
原文:https://www.pythonforbeginners.com/basics/python-bitwise-operators
Python 中有各种类型的运算符,如算术运算符、比较运算符和位运算符。在我们的程序中,我们使用这些操作符来控制执行顺序和操作数据。在本文中,我们将研究不同的 python 位操作符,它们的功能和例子。
什么是按位运算符?
通常,我们在程序中使用算术运算符对数字的十进制值进行计算。但是,我们也可以对二进制形式的数字进行运算。为此,我们使用按位运算符。正如您可以从名称中预测的那样,按位运算符一点一点地处理数据。当我们对十进制形式的数字执行任何位运算时,这些数字被转换成二进制数,然后执行位运算。此外,位运算只能在可能是正数或负数的整数上执行。
以下是 Python 中的按位运算符表。
| 操作 | 操作员 |
| 和 | & |
| 运筹学 | | |
| 不 | ~ |
| 异或运算 | ^ |
Python Bitwise Operators
为了理解按位运算符的工作原理,我建议您理解十进制数到二进制数的转换。在本文中,我们将使用两个整数 8 和 14 来执行位运算。
8 以二进制形式表示为 1000 ,而 14 以二进制形式表示为 1110 。在 python 中,二进制数由 0 和 1 的序列表示,前面是“0b”。我们可以很容易地使用 bin()函数将十进制数转换成二进制数,如下所示。
myNum1 = 8
binNum1 = bin(myNum1)
myNum2 = 14
binNum2 = bin(myNum2)
print("Binary of {} is {}.".format(myNum1, binNum1))
print("Binary of {} is {}.".format(myNum2, binNum2))
输出:
Binary of 8 is 0b1000.
Binary of 14 is 0b1110.
Python 中的按位 AND
按位 AND 是二元按位运算符。换句话说,按位 AND 运算符对两个操作数的位表示进行运算。在按位 AND 运算中,如果两个操作数都为 1,则输出位为 1。否则,输出位为 0。按位 AND 运算符的工作可以总结为以下规则。
- 0 和 0 = 0
- 0 和 1 = 0
- 1 和 0 = 0
- 1 和 1 = 1
让我们用下面的例子来理解这一点。假设我们必须对 8 和 14 执行按位 AND 运算。我们首先将它转换成二进制格式。
- 二进制格式的 8 写成 1000。
- 二进制格式的 14 写成 1110。
为了对这两个数执行按位 AND 运算,我们将从最右边的位开始对这两个数的位逐一执行按位 AND 运算。我们将最右边的位称为第一位,第二个最右边的位称为第二位,第三个最右边的位称为第三位,依此类推。由于 8 和 14 都有四位,我们将逐一对所有位执行按位 and 运算。
- 对两个数的第一位进行按位 AND 运算。
0 和 0 =0
- 两个数的第二位的按位 AND。
0 和 1=0
- 两个数的第三位的按位 AND。
0 和 1=0
- 两个数的第四位的按位 AND。
1 和 1=1
因此,在输出中,第一位是 0,第二位是 0,第三位是 0,第四位是 1。即二进制格式的输出将是 1000,这将是整数格式的数字 8。我们可以使用下面的程序在 python 中使用 AND 运算符来验证这个输出。
myNum1 = 8
myNum2 = 14
andNum = myNum1 & myNum2
print("Operand 1 is:", myNum1)
print("operand 2 is:", myNum2)
print("Result of the AND operation on {} and {} is {}.".format(myNum1, myNum2, andNum))
输出:
Operand 1 is: 8
operand 2 is: 14
Result of the AND operation on 8 and 14 is 8.
Python 中的按位 OR
按位 OR 是二元按位运算符。换句话说,按位 OR 运算符对两个操作数的位表示进行运算。在按位“或”运算中,如果任一操作数为 1,则输出位为 1。否则,输出位为 0。按位“或”运算符的工作可以总结为以下规则。
- 0 或 0 = 0
- 0 或 1 = 1
- 1 或 0 = 1
- 1 或 1 = 1
让我们用下面的例子来理解这一点。
假设我们必须对 8 和 14 执行按位“或”运算。我们首先将它转换成二进制格式。
- 二进制格式的 8 写成 1000。
- 二进制格式的 14 写成 1110。
为了对这两个数执行按位“或”运算,我们将从最右边的位开始,对这两个数的位逐一执行按位“或”运算。我们将最右边的位称为第一位,第二个最右边的位称为第二位,第三个最右边的位称为第三位,依此类推。
由于 8 和 14 都有四位,我们将逐一对所有位执行按位“或”运算。
- 两个数的第一位按位或。
0 或 0 =0
- 两个数的第二位的按位“或”。
0 或 1=1
- 两个数的第三位的按位“或”。
0 或 1=1
- 两个数的第四位的按位“或”。
1 或 1=1
因此,在输出中,第一位是 0,第二位是 1,第三位是 1,第四位是 1。即二进制格式的输出将是 1110,这将是整数格式的数字 14。我们可以使用下面的程序在 python 中使用 OR 运算符来验证这个输出。
myNum1 = 8
myNum2 = 14
orNum = myNum1 | myNum2
print("Operand 1 is:", myNum1)
print("operand 2 is:", myNum2)
print("Result of the OR operation on {} and {} is {}.".format(myNum1, myNum2, orNum))
输出:
Operand 1 is: 8
operand 2 is: 14
Result of the OR operation on 8 and 14 is 14.
Python 中的按位 NOT
按位 NOT 是一元按位运算符。换句话说,按位 NOT 运算符对其位表示中的一个操作数起作用。在按位非运算中,如果输入位为 0,则输出位为 1,如果输入位为 1,则输出为 0。按位 NOT 运算符的工作可以总结为以下规则。
- 不是 0 = 1
- 不是 1= 0
让我们用下面的例子来理解这一点。
假设我们必须对 14 执行按位非运算。我们首先将它转换成二进制格式。
- 二进制格式的 14 写成 1110。
要对 14 执行按位非运算,我们将从最右边的位开始,对数字的每个位逐一执行按位非运算。我们将最右边的位称为第一位,第二个最右边的位称为第二位,第三个最右边的位称为第三位,依此类推。
由于 14 中有四位,我们将对所有位逐一执行按位非运算。
- 第一位的按位非。
不是 0 = 1。
- 第二位的按位非。
不是 1 = 0。
- 第三位的按位非。
不是 1 = 0。
- 第四位的按位非。
不是 1 = 0。
因此,在输出中,第一位是 1,第二位是 0,第三位是 0,第四位是 0。即二进制格式的输出将是 0001,这将是整数格式的数字 1。
myNum1 = 14
notNum = ~myNum1
print("Operand 1 is:", myNum1)
print("Result of the NOT operation on {} is {}.".format(myNum1, notNum))
输出:
Operand 1 is: 14
Result of the NOT operation on 14 is -15.
等等,NOT 运算的输出是-15。但是,根据我们的理论应该是 1。哪里出问题了?
哪儿也不去。NOT 是一个按位求逆运算符,x 的按位求逆在 Python 中定义为-(x+1)。这里 x 是输入的数字。我将在接下来的章节中更多地讨论一个人的补充。
Python 中的 XOR
按位异或是一种二进制按位运算符。换句话说,按位 XOR 运算符对两个操作数的位表示进行运算。在按位异或运算中,如果两位相同,结果将为 0,否则,结果将为 1。
我们可以用 AND、OR 和 NOT 运算符来写 XOR,如下所示。
a XOR b = (b 与(非 a))或(a 与(非 b))
按位 XOR 运算符的工作可以总结为以下规则。
- 1 异或 0 = 1
- 1 异或 1 = 0
- 0 异或 0 = 0
- 1 异或 0 = 1
让我们用下面的例子来理解这一点。
假设我们必须对 8 和 14 执行按位异或运算。我们首先将它转换成二进制格式。
- 二进制格式的 8 写成 1000。
- 二进制格式的 14 写成 1110。
为了对这两个数执行按位 XOR 运算,我们将从最右边的位开始对这两个数的位逐一执行按位 XOR 运算。我们将最右边的位称为第一位,第二个最右边的位称为第二位,第三个最右边的位称为第三位,依此类推。
由于 8 和 14 都有四位,我们将逐一对所有位执行按位异或运算。
- 两个数的第一位按位异或。
0 异或 0 =0
- 两个数字的第二位按位异或。
0 或 1=1
- 两个数的第三位按位异或。
- 0 或 1=1
- 两个数字的第四位按位异或。
1 或 1=0
因此,在输出中,第一位是 0,第二位是 1,第三位是 1,第四位是 0。即二进制格式的输出将是 0110,这将是整数格式的数字 6。我们可以使用下面的程序在 python 中使用 XOR 运算符来验证这个输出。
myNum1 = 8
myNum2 = 14
xorNum = myNum1 ^ myNum2
print("Operand 1 is:", myNum1)
print("operand 2 is:", myNum2)
print("Result of the XOR operation on {} and {} is {}.".format(myNum1, myNum2, xorNum))
输出:
Operand 1 is: 8
operand 2 is: 14
Result of the XOR operation on 8 and 14 is 6.
结论
在本文中,我们讨论了 python 按位运算符、它们的语法和例子。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 备忘单
原文:https://www.pythonforbeginners.com/cheatsheet/python-cheat-sheets
在 PythonForBeginners,我们整理了一些 Python 备忘单,希望与读者分享。你可以在页面顶部找到大部分的备忘单,但是还有更多…为了更容易找到,我们列出了到目前为止我们写的所有备忘单。
Python 基础知识
字典
列表
琴弦
循环(for 和 while)
文件处理
功能
模块
机械化
Python 代码:摄氏和华氏转换器
概观
这个脚本将华氏温度转换为摄氏温度。要创建摄氏和华氏的 python 转换器,首先必须找出要使用哪个公式。
华氏温度到摄氏温度的公式:
(F–32)x 5/9 = C 或者说白了,先减去 32,再乘以 5,再除以 9。
摄氏至华氏公式:
(C × 9/5) + 32 = F 或者说白了,乘以 9,再除以 5,再加 32。
将华氏温度转换为摄氏温度
#!/usr/bin/env python
Fahrenheit = int(raw_input("Enter a temperature in Fahrenheit: "))
Celsius = (Fahrenheit - 32) * 5.0/9.0
print "Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C"
将摄氏温度转换为华氏温度
#!/usr/bin/env python
Celsius = int(raw_input("Enter a temperature in Celsius: "))
Fahrenheit = 9.0/5.0 * Celsius + 32
print "Temperature:", Celsius, "Celsius = ", Fahrenheit, " F"
阅读并理解剧本。快乐脚本!
Python 代码:将 KM/H 转换为 MPH
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-code-convert-kmh-to-mph
将公里/小时转换为英里/小时
This script converts speed from KM/H to MPH, which may be handy for calculating
speed limits when driving abroad, especially for UK and US drivers.
The conversion formula for kph to mph is : 1 kilometre = 0.621371192 miles
#!/usr/bin/env python
kmh = int(raw_input("Enter km/h: "))
mph = 0.6214 * kmh
print "Speed:", kmh, "KM/H = ", mph, "MPH"
Python 代码示例
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-code-examples
这个页面包含了我们到目前为止在网站上发布的所有 Python 脚本。
例题
pywhois 是一个 Python 模块,用于检索域名的 whois 信息。pywhois 与 Python 2.4+一起工作,没有外部依赖【源】
在这个脚本中,我使用了 8 个可能的答案,但请随意添加更多。魔法 8 球里面有 20 个答案,你可以在这里全部找到。
当您想要使用基于 Web 的服务时,常见的第一步是查看它们是否有 API。幸运的是,Commandlinefu.com提供了一个,可以在这里找到
用 os.walk 和 fnmatch 找到所有 mp3 文件
在之前的一篇文章“Python 中的 OS.walk”中,我描述了如何使用 os.walk,并展示了一些如何在脚本中使用它的例子。在本文中,我将展示如何使用 os.walk()模块函数遍历目录树,以及使用 fnmatch 模块匹配文件名。
这篇文章将展示如何用 Python 编写一个小巧易用的端口扫描程序。
备份所有 MySQL 数据库,带时间戳。
使用 ConfigParser 备份所有 MySQL 数据库,每个文件一个,最后带有时间戳。
为了向 Web 搜索 API 发出请求,我们必须导入我们需要的模块。
Pxssh 基于 pexpect。它的类扩展了 pexpect.spawn 来专门设置 SSH 连接。
这个脚本可以用来解析日期和时间。
Bitly 允许用户缩短、共享和跟踪链接(URL)。这是一种保存、分享和发现网络链接的方式。
smtplib 模块定义了一个 SMTP 客户端会话对象,该对象可用于将
邮件发送到任何带有 SMTP 或 ESMTP 监听器守护进程的互联网机器。SMTP 代表简单邮件传输协议。
这个简短的脚本使用 os.listdir 函数(属于 os 模块)来搜索给定的路径(".)用于所有以“”结尾的文件。txt”。
Speedtest.net 是一个连接分析网站,用户可以在这里对分布在世界各地的数百台服务器测试他们的网速。
在本文中,我将展示如何使用 os.walk()模块函数遍历
目录树,以及使用 fnmatch 模块匹配文件名。
当您想从各种 web 服务访问一个 API
并以 JSON 给出响应时,知道如何解析 JSON 对象是很有用的。
又到了脚本的时间了,这个脚本将根据用户的输入地理定位一个 IP 地址。对于这个脚本,我们将使用一组 Python 模块来完成这个任务。
这个脚本将使用 raw_input 函数要求用户输入用户名。然后创建一个名为 user1 和 user2 的允许用户列表。控制语句检查来自用户的输入是否与允许用户列表中的输入相匹配。
这个脚本将使用 Twitter API 来搜索推文。
在这篇文章中,我将向你展示如何不用它,只需使用
datetime.datetime.now()。
这篇文章的第二部分是关于 timedelta 类,在这个类中,我们可以看到两个日期、时间或日期时间实例之间微秒级分辨率的差异。
这是一个经典的“掷骰子”程序。
这个小脚本将计算 Apache/Nginx 日志文件中的点击次数。
该脚本将显示日志文件
变量中指定的文件中的所有条目。
在这篇文章中,我将向您展示如何通过使用 datetime.datetime.now()打印出日期和时间。
这个小程序扩展了我之前在这个
里写过的猜谜游戏:贴“猜谜游戏”。
这个脚本是一个交互式猜谜游戏,它将要求用户猜一个 1 到 99 之间的
数字。
可以使用python 字符串和随机模块生成密码。
OS.walk()通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。
这个脚本将速度从 KM/H 转换为 MPH,这对于计算国外驾驶时的速度限制可能很方便,特别是对于英国和美国的司机。
在这个脚本中,我们将使用 re 模块从任何网站获取所有链接。
这个脚本将华氏温度转换为摄氏温度。
在这篇文章中,我们将学习如何在 Python 中使用 Vimeo API。
这个程序将展示我们如何使用 API 从 YouTube 中检索提要。
这个脚本将计算三个值的平均值。
这是一个简单的 Python 脚本,用于检查您拥有哪个外部 IP 地址。
这是一个经典游戏《刽子手》的 Python 脚本。
这个脚本将要求输入电影名称和年份,然后向 IMDB 查询。
Python 代码示例
在这里,我们链接到提供 Python 代码示例的其他站点。
snipplr . com
Python 集合计数器
原文:https://www.pythonforbeginners.com/collection/python-collections-counter
收集模块概述
Collections 模块实现了高性能的容器数据类型(超越了
内置的类型 list、dict 和 tuple ),并包含许多有用的数据结构
,您可以使用它们在内存中存储信息。
本文将讨论计数器对象。
计数器
计数器是一个跟踪等效值相加的次数的容器。
它可以用来实现其他语言通常使用包或多重集数据结构的算法。
导入模块
导入收藏使收藏中的内容可用:
collections.something
import collections
因为我们只打算使用计数器,所以我们可以简单地这样做:
from collections import Counter
正在初始化
计数器支持三种形式的初始化。
它的构造函数可以用一个项目序列(iterable)、一个包含键和计数的字典
来调用(映射,或者使用关键字参数将字符串
名称映射到计数(关键字参数)。
import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
所有三种初始化形式的结果都是相同的。
$ python collections_counter_init.py
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
创建和更新计数器
可以构造一个没有参数的空计数器,并通过
update()方法填充。
import collections
c = collections.Counter()
print 'Initial :', c
c.update('abcdaab')
print 'Sequence:', c
c.update({'a':1, 'd':5})
print 'Dict :', c
计数值基于新数据而增加,而不是被替换。
在这个例子中,a 的计数从 3 到 4。
$ python collections_counter_update.py
Initial : Counter()
Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})
访问计数器
一旦填充了计数器,就可以使用字典 API 检索它的值。
import collections
c = collections.Counter('abcdaab')
for letter in 'abcde':
print '%s : %d' % (letter, c[letter])
计数器不会引发未知项目的 KeyError。
如果在输入中没有看到一个值(如本例中的 e),
其计数为 0。
$ python collections_counter_get_values.py
a : 3
b : 2
c : 1
d : 1
e : 0
元素
elements()方法返回一个遍历元素的迭代器,每个元素重复的次数与它的计数一样多。
元素以任意顺序返回。
import collections
c = collections.Counter('extremely')
c['z'] = 0
print c
print list(c.elements())
不保证元素的顺序,计数小于零的项目
不包括在内。
$ python collections_counter_elements.py
Counter({'e': 3, 'm': 1, 'l': 1, 'r': 1, 't': 1, 'y': 1, 'x': 1, 'z': 0})
['e', 'e', 'e', 'm', 'l', 'r', 't', 'y', 'x']
最常见的
使用 most_common()生成 n 个最常出现的
输入值及其各自计数的序列。
import collections
c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print 'Most common:'
for letter, count in c.most_common(3):
print '%s: %7d' % (letter, count)
本示例对系统
词典中所有单词出现的字母进行计数,以产生一个频率分布,然后打印三个最常见的
字母。
省略 most_common()的参数会产生一个所有条目的列表,按照频率的顺序排列。
$ python collections_counter_most_common.py
Most common:
e: 234803
i: 200613
a: 198938
算术
计数器实例支持用于聚合结果的算术和集合运算。
import collections
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print 'C1:', c1
print 'C2:', c2
print '
Combined counts:'
print c1 + c2
print '
Subtraction:'
print c1 - c2
print '
Intersection (taking positive minimums):'
print c1 & c2
print '
Union (taking maximums):'
print c1 | c2
每次通过操作产生一个新的计数器时,任何零计数或负计数的项目都将被丢弃。
c1 和 c2 中 a 的计数是相同的,所以减法使其为零。
$ python collections_counter_arithmetic.py
C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'b': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
#Combined counts:
Counter({'a': 4, 'b': 4, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
#Subtraction:
Counter({'b': 2, 'c': 1})
#Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})
#Union (taking maximums):
Counter({'b': 3, 'a': 2, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
计数单词
统计单词在列表中的出现次数。
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
print cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
计数器接受一个 iterable,也可以这样写:
mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
cnt = Counter(mywords)
print cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
找出最常见的单词
找出哈姆雷特中最常见的十个单词
import re
words = re.findall('w+', open('hamlet.txt').read().lower())
print Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
来源
请不要忘记阅读下面的链接了解更多信息。
http://www.doughellmann.com/PyMOTW/collections/
http://docs . python . org/2/library/collections . html # collections。柜台
Python 比较运算符
原文:https://www.pythonforbeginners.com/basics/python-comparison-operator
Python 中有各种类型的运算符,如算术运算符、比较运算符和位运算符。在我们的程序中,我们使用这些操作符来控制执行顺序和操作数据。在本文中,我们将研究不同 python 比较操作符、它们的功能和例子。
什么是 Python 比较运算符?
比较运算符是用于比较程序中两个对象的二元运算符。这些操作符也称为关系操作符,因为它们决定了 python 中两个对象之间的关系。
比较运算符在比较操作数后返回布尔值“真”或“假”。
Python 等于运算符
Python 等于运算符用于检查两个对象是否相等。
python 中等于运算符的语法是 a == b。这里 a 和 b 是正在进行相等性检查的操作数。变量 a 和 b 可以包含具有诸如整数、浮点或字符串之类的原始数据类型的任何对象,或者它们可以包含对诸如列表、元组、集合和字典之类的容器对象的引用。如果两个操作数相等,则输出为真。否则,输出将为假。
您可以使用下面的程序来理解等于运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 == myNum2
compare13 = myNum1 == myNum3
compare14 = myNum1 == myNum4
print("{} is equal to {}?: {}".format(myNum1, myNum2, compare12))
print("{} is equal to {}?: {}".format(myNum1, myNum3, compare13))
print("{} is equal to {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is equal to 14?: True
14 is equal to 10?: False
14 is equal to 5?: False
Python 不等于运算符
Python 不等于运算符用于检查两个对象是否不相等。
python 中等于运算符的语法是!= b。这里 a 和 b 是被检查是否不相等的操作数。变量 a 和 b 可以包含具有诸如整数、浮点或字符串之类的原始数据类型的任何对象,或者它们可以包含对诸如列表、元组、集合和字典之类的容器对象的引用。如果两个操作数相等,则输出为假。否则,输出将为真。
使用下面的程序,你可以理解不等于运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 != myNum2
compare13 = myNum1 != myNum3
compare14 = myNum1 != myNum4
print("{} is not equal to {}?: {}".format(myNum1, myNum2, compare12))
print("{} is not equal to {}?: {}".format(myNum1, myNum3, compare13))
print("{} is not equal to {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is not equal to 14?: False
14 is not equal to 10?: True
14 is not equal to 5?: True
Python 小于运算符
Python 小于运算符用于检查一个对象是否小于另一个对象。
python 中小于运算符的语法是 a < b。变量 a 和 b 可以包含任何具有整数、浮点或字符串等原始数据类型的对象,也可以包含对列表、元组、集和字典等容器对象的引用。如果 a 小于 b,则输出为真,否则输出为假。
使用下面的程序,您可以理解小于运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 < myNum2
compare13 = myNum3 < myNum1
compare14 = myNum1 < myNum4
print("{} is less than {}?: {}".format(myNum1, myNum2, compare12))
print("{} is less than {}?: {}".format(myNum3, myNum1, compare13))
print("{} is less than {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is less than 14?: False
10 is less than 14?: True
14 is less than 5?: False
小于运算符不支持字符串和数字数据类型(如 float 或 int)之间的比较。如果我们尝试执行这样的比较,将会出现 TypeError。你可以使用除了块之外的 python try 来避免它。
Python 大于运算符
Python 大于运算符用于检查一个对象是否大于另一个对象。
python 中大于运算符的语法是 a > b。变量 a 和 b 可以包含任何具有整数、浮点或字符串等原始数据类型的对象,也可以包含对列表、元组、集和字典等容器对象的引用。如果 a 大于 b,则输出为真,否则输出为假。
使用下面的程序,您可以理解大于号运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 > myNum2
compare13 = myNum1 > myNum3
compare14 = myNum1 > myNum4
print("{} is greater than {}?: {}".format(myNum1, myNum2, compare12))
print("{} is greater than {}?: {}".format(myNum1, myNum3, compare13))
print("{} is greater than {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is greater than 14?: False
14 is greater than 10?: True
14 is greater than 5?: True
大于运算符不支持字符串和数字数据类型(如 float 或 int)之间的比较。如果我们尝试执行这样的比较,将会出现 TypeError。
Python 小于或等于
Python 小于或等于运算符用于检查一个对象是否小于或等于另一个对象。
python 中小于或等于运算符的语法是 a <= b。变量 a 和 b 可以包含任何具有整数、浮点或字符串等原始数据类型的对象,也可以包含对列表、元组、集和字典等容器对象的引用。如果 a 小于或等于 b,则输出为真,否则输出为假。
您可以使用下面的程序来理解小于或等于运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 <= myNum2
compare13 = myNum3 <= myNum1
compare14 = myNum1 <= myNum4
print("{} is less than or equal to {}?: {}".format(myNum1, myNum2, compare12))
print("{} is less than or equal to {}?: {}".format(myNum3, myNum1, compare13))
print("{} is less than or equal to {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is less than or equal to 14?: True
10 is less than or equal to 14?: True
14 is less than or equal to 5?: False
Python 大于或等于
Python 大于或等于运算符用于检查一个对象是否大于或等于另一个对象。
python 中大于或等于运算符的语法是 a >= b。变量 a 和 b 可以包含任何具有整数、浮点或字符串等原始数据类型的对象,也可以包含对列表、元组、集和字典等容器对象的引用。如果 a 大于或等于 b,则输出为真,否则输出为假。
您可以使用下面的程序理解大于或等于运算符的工作原理。
myNum1 = 14
myNum2 = 14
myNum3 = 10
myNum4 = 5
compare12 = myNum1 >= myNum2
compare13 = myNum1 >= myNum3
compare14 = myNum1 >= myNum4
print("{} is greater than or equal to {}?: {}".format(myNum1, myNum2, compare12))
print("{} is greater than or equal to {}?: {}".format(myNum1, myNum3, compare13))
print("{} is greater than or equal to {}?: {}".format(myNum1, myNum4, compare14))
输出:
14 is greater than or equal to 14?: True
14 is greater than or equal to 10?: True
14 is greater than or equal to 5?: True
结论
在本文中,我们讨论了每一个 python 比较操作符。我们还讨论了一些示例以及在使用每个 python 比较运算符执行比较时可能出现的错误。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的条件语句
原文:https://www.pythonforbeginners.com/basics/python-conditional-statements
条件语句
在编程中,我们经常想要检查条件并改变程序的
行为。
如何使用条件语句
我们可以根据一个变量的值编写有不止一个动作选择的程序。
也许最广为人知的语句类型是 if 语句。
如果一件事为真,使用 if 语句执行一个动作;如果另一件事为真,使用
语句执行任意数量的其他动作。
我们必须使用缩进来定义执行的代码,基于是否满足条件。
为了在 Python 中比较数据,我们可以使用比较操作符,在
中找到这个布尔,真或假帖子。
如果语句
if 语句的语法是:
if 表达式:
语句
Elif 语句
有时有两种以上的可能性,在这种情况下我们可以使用
elif 语句
它代表“else if”,这意味着如果原始 if 语句为
false,而 elif 语句为 true,则执行
elif 语句之后的代码块。
if…elif 语句的语法是:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Else 语句
else 语句可以与 if 语句结合使用。
else 语句包含在 if 语句中的条件
表达式解析为 0 或 false 值时执行的代码块。
else 语句是可选语句,if 后面最多只能有一个
else 语句。
if 的语法..else 是:
if expression:
statement(s)
else:
statement(s)
例子
这个脚本将根据用户的输入比较两个字符串
# This program compares two strings.
# Get a password from the user.
password = raw_input('Enter the password: ')
# Determine whether the correct password
# was entered.
if password == 'hello':
print'Password Accepted'
else:
print'Sorry, that is the wrong password.'
另一个例子
让我们再展示一个例子,其中也将使用 elif 语句。
#!/usr/bin/python
number = 20
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
elif guess < number:
print('No, it is a little higher than that')
else:
print('No, it is a little lower than that')
如何在 Python 中使用日期和时间
原文:https://www.pythonforbeginners.com/basics/python-datetime-time-examples
日期和时间
这篇文章将展示一些使用 Pythons 日期时间和时间模块的例子。
在之前的一篇文章Python 中的基本日期和时间类型中,我写道,datetime 和 time 对象都支持 strftime(format)方法来创建一个在显式格式字符串控制下表示时间的字符串。
日期和时间示例
让我们看看可以用 Python 中的 datetime 和 time 模块做些什么
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
输出
它会打印出这样的内容:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
获取某个日期的星期几(你的宠物的生日)。
import datetime
mydate = datetime.date(1943,3, 13) #year, month, day
print(mydate.strftime("%A"))
Python 中的日期和时间
原文:https://www.pythonforbeginners.com/basics/python-datetime-timedelta
Python 中的日期和时间
在我上一篇关于 Python 中的 datetime & time 模块的文章中,我主要使用 strftime(format)方法来打印日期和时间。
在这篇文章中,我将向您展示如何不用它,只使用 datetime.datetime.now()就能做到。
文章的第二部分是关于 timedelta 类,在这个类中,我们可以看到两个日期、时间或日期时间实例之间微秒级分辨率的差异。
日期和时间脚本
最后一个例子是一个简短的脚本,用于计算给定日期(本例中是生日)还剩多少天。
import datetime
now = datetime.datetime.now()
print "-" * 25
print now
print now.year
print now.month
print now.day
print now.hour
print now.minute
print now.second
print "-" * 25
print "1 week ago was it: ", now - datetime.timedelta(weeks=1)
print "100 days ago was: ", now - datetime.timedelta(days=100)
print "1 week from now is it: ", now + datetime.timedelta(weeks=1)
print "In 1000 days from now is it: ", now + datetime.timedelta(days=1000)
print "-" * 25
birthday = datetime.datetime(2012,11,04)
print "Birthday in ... ", birthday - now
print "-" * 25
您应该会看到类似于以下内容的输出:
-------------------------
2012-10-03 16:04:56.703758
2012
10
3
16
4
56
-------------------------
The date and time one week ago from now was: 2012-09-26 16:04:56.703758
100 days ago was: 2012-06-25 16:04:56.703758
One week from now is it: 2012-10-10 16:04:56.703758
In 1000 days from now is it: 2015-06-30 16:04:56.703758
-------------------------
Birthday in ... 31 days, 7:55:03.296242
-------------------------
我在 saltycrane.com 发现了这篇我喜欢并想分享的博文:http://www . salty crane . com/blog/2008/06/how-to-get-current-date-time-in/
Python 装饰者
原文:https://www.pythonforbeginners.com/basics/python-decorators
Python 为我们提供了许多执行不同任务的结构。在编程时,有时我们可能需要修改函数的工作方式。但是我们可能不被允许改变函数的源代码,因为它可能在程序中以其原始形式被使用。在这种情况下,可以使用 Python decorators。
在本文中,我们将研究什么是 Python decorators,我们如何创建 decorator,以及我们如何使用它们来修改 Python 中其他函数的功能。
什么是 Python 装饰者?
Python decorators 是函数或其他可调用的对象,可用于向另一个函数添加功能,而无需修改其源代码。python 中的 decorator 接受一个函数作为输入参数,向它添加一些功能,然后返回一个包含修改后的功能的新函数。
在 python 中实现 decorators 需要了解不同的概念,比如第一类对象和嵌套函数。首先,我们将看看这些概念,这样我们在理解 python decorators 的实现时就不会遇到问题。
理解装饰者所需的概念
第一类对象
在 Python 中,第一类对象是那些
- 可以作为参数传递给函数。
- 可以从函数中返回。
- 可以赋给一个变量。
我们在程序中使用的所有变量都是第一类对象,无论它是原始数据类型、集合对象还是使用类定义的对象。
这里我想强调一下,python 中的函数也是第一类对象,我们可以传递一个函数作为输入参数,也可以从一个函数返回一个函数。
例如,让我们看看下面的源代码。
这里,我们定义了一个函数 add() ,它将两个数字作为输入,并打印它们的和。我们定义了另一个函数 random_adder (),它以一个函数为输入,随机生成两个数字,并调用输入函数 add (),将随机生成的数字作为输入。
import random
def add(num1, num2):
value = num1 + num2
print("In the add() function. The sum of {} and {} is {}.".format(num1, num2, value))
def random_adder(func):
val1 = random.randint(0, 10)
val2 = random.randint(0, 100)
print("In the random_adder. Values generated are {} and {}".format(val1, val2))
func(val1, val2)
# execute
random_adder(add)
输出:
In the random_adder. Values generated are 1 and 14
In the add() function. The sum of 1 and 14 is 15.
从代码和输出中,您可以观察到函数 add() 已经作为输入传递给了 random_adder ()函数,并且 random_adder ()函数调用了打印输出的函数。
我们也可以从另一个函数或可调用对象返回一个函数。例如,我们可以修改上面的源代码,在 random_adder ()函数中定义一个函数 operate ()。 operate ()函数执行前面源代码中 random_adder ()函数完成的全部操作。
现在我们可以从 random_adder ()函数中返回 operate ()函数,并赋给一个名为 do_something 的变量。这样,我们就可以在 random_adder ()函数之外,通过调用变量 do_something 来执行 operate ()函数,如下所示。
*`import random
def add(num1, num2):
value = num1 + num2
print("In the add() function. The sum of {} and {} is {}.".format(num1, num2, value))
def random_adder(func):
print("In the random_adder.")
def operate():
val1 = random.randint(0, 10)
val2 = random.randint(0, 100)
print("In the operate() function. Values generated are {} and {}".format(val1, val2))
func(val1, val2)
print("Returning the operate() function.")
return operate
# execute
do_something = random_adder(add)
do_something()`*
输出:
*`In the random_adder.
Returning the operate() function.
In the operate() function. Values generated are 3 and 25
In the add() function. The sum of 3 and 25 is 28.`*
嵌套函数
嵌套函数是定义在另一个函数内部的函数。例如,看看下面的源代码。
这里,我们定义了一个函数 add (),它将两个数字作为输入,并计算它们的和。此外,我们在()中定义了函数 square ()来打印在 add ()函数中计算的“ 值 ”的平方。**
**`def add(num1, num2):
value = num1 + num2
print("In the add() function. The sum of {} and {} is {}.".format(num1, num2, value))
def square():
print("I am in square(). THe square of {} is {}.".format(value, value ** 2))
print("calling square() function inside add().")
square()
# execute
add(10, 20)`**
输出:
**`In the add() function. The sum of 10 and 20 is 30.
calling square() function inside add().
I am in square(). THe square of 30 is 900.`**
自由变量
我们知道一个变量可以在它被定义的范围内被访问。但是,在嵌套函数的情况下,当我们在内部函数中时,我们可以访问封闭函数的元素。
在上面的例子中,你可以看到我们在 add ()函数中定义了变量“ value ”,但是我们在 square ()函数中访问了它。这些类型的变量被称为自由变量。
但是为什么叫自由变量呢?
因为即使定义它的函数已经完成了它的执行,也可以访问它。例如,看看下面给出的源代码。
**`def add(num1, num2):
value = num1 + num2
print("In the add() function. The sum of {} and {} is {}.".format(num1, num2, value))
def square():
print("I am in square(). THe square of {} is {}.".format(value, value ** 2))
print("returning square() function.")
return square
# execute
do_something = add(10, 20)
print("In the outer scope. Calling do_something.")
do_something()`**
输出:
**`In the add() function. The sum of 10 and 20 is 30.
returning square() function.
In the outer scope. Calling do_something.
I am in square(). THe square of 30 is 900.`**
这里,一旦 add ()函数返回 square ()函数,它就完成了它的执行,并从内存中被清除。尽管如此,我们还是可以通过调用已经赋给变量 do_something 的 square ()函数来访问变量 value 。
既然我们已经讨论了实现 python decorators 所需的概念,那么让我们深入研究一下如何实现 decorator。
如何创建 Python Decorators?
我们可以使用任何可调用对象来创建 python decorators,这些对象可以接受一个可调用对象作为输入参数,并且可以返回一个可调用对象。在这里,我们将使用 Python 中的函数创建 decorators。
对于要成为装饰器的函数,它应该遵循以下属性。
- 它必须接受一个函数作为输入。
- 它必须包含嵌套函数。
- 它必须返回一个函数。
首先,我们将定义一个函数 add (),它将两个数字作为输入,并打印它们的和。
**`def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)`**
输出:
**`The sum of 10 and 20 is 30.`**
现在,我们必须以这样的方式定义一个装饰器,即 add ()函数还应该打印数字的乘积以及总和。为此,我们可以创建一个装饰函数。
让我们首先定义一个函数,它将 add ()函数作为输入,并用附加的需求来修饰它。
**`def decorator_function(func):
def inner_function(*args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
func(args[0], args[1])
return inner_function`**
在decorator _ function(),我们定义了 inner_function (),它打印作为输入给出的数字的乘积,然后调用 add ()函数。decorator _ function()返回inner _ function()。
既然我们已经定义了decorator _ function()和 add ()函数,那么让我们看看如何使用decorator _ function()来修饰 add ()函数。
通过将函数作为参数传递给另一个函数来创建 Python 装饰器
修饰 add ()函数的第一种方法是将其作为输入参数传递给decorator _ function()。一旦decorator _ function()被调用,它将返回inner _ function()并赋给变量 do_something 。之后,变量 do_something 将变为可调用,并在被调用时执行inner _ function()内的代码。由此,我们可以调用 do_something 来打印输入数字的乘积和之和。
**`def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
def decorator_function(func):
def inner_function(*args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
func(args[0], args[1])
return inner_function
# execute
do_something = decorator_function(add)
do_something(10, 20)`**
输出:
**`Product of 10 and 20 is 200
The sum of 10 and 20 is 30.`**
使用@ sign 创建 Python 装饰器
执行相同操作的一个更简单的方法是使用“@”符号。我们可以指定decorator _ function的名称,在 @ 符号之前定义 添加 ()函数。此后,每当调用 add ()函数时,它总是打印输入数字的乘积和总和。
**`def decorator_function(func):
def inner_function(*args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return func(args[0], args[1])
return inner_function
@decorator_function
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)`**
输出:
**`Product of 10 and 20 is 200
The sum of 10 and 20 is 30.`**
这种方法有一个缺点,就是不能用 加 ()函数只是把数字相加。它总是打印数字的乘积以及它们的总和。因此,通过正确地分析您的需求,选择您将要用来实现装饰器的方法。
结论
在本文中,我们讨论了什么是 python 装饰器,以及我们如何使用 Python 中的函数来实现它们。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 字典的基本用法
原文:https://www.pythonforbeginners.com/dictionary/python-dictionary-basic-usage
Dictionary 是 Python 中的另一种数据类型。
字典概述
A dictionary maps a set of key to a set of values.
Dictionaries in Python are also known as hash tables.
It requires that the keys are unique (within one dictionary), while the values maynot.
The values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Dictionaries are like lists mutable
A dictionary is created with a pair of braces {}.
For example, dic = {} creates an empty dictionary.
Each key is separated from its value by a colon (:)
Placing a comma-separated list of key:value pairs within the braces adds initial
key:value pairs to the dictionary; this is also the way dictionaries are written
on output.
The main operations on a dictionary are storing a value with some key and
extracting the value given the key.
If you store using a key that is already in use, the old value associated with
that key is forgotten.
别忘了查看字典备忘单
Python 字典快速指南
原文:https://www.pythonforbeginners.com/dictionary/python-dictionary-quick-guide
如题,这是一本 Python 字典快速指南。
请查看字典教程了解更多关于字典的文章。
# key/value pairs declaration
dict = {
‘key1′:’value1′,
‘key2′:’value2′,
‘key3′:’value3′
}
#Get all keys
dict.keys()
#Get all values
dict.values()
#Modifying
dict['key2'] = ‘value8′
#Accessing
print dict['key1']
# prints ‘value2′
print dict['key2']
# empty declaration + assignment of key-value pair
emptyDict = {}
emptyDict['key4']=’value4′
# looping through dictionaries (keys and values)
for key in dict:
print dict[key]
# sorting keys and accessing their value in order
keys = dict.keys()
keys.sort()
for key in keys:
print dict[key]
# looping their values directory (not in order)
for value in dict.values():
print value
# getting both the keys and values at once
for key,value in dict.items():
print “%s=%s” % (key,value)
# deleting an entry
del dict['key2']
# delete all entries in a dictionary
dict.clear()
# size of the dictionary
len(dict)
python 文档字符串
原文:https://www.pythonforbeginners.com/basics/python-docstrings
什么是 Docstring?
Python 文档字符串(或文档字符串)提供了一种将文档与 Python 模块、函数、类和方法相关联的便捷方式。
通过将字符串常量作为对象定义中的第一条语句来定义对象的文档。它是在源代码中指定的,像注释一样,用来记录特定的代码段。
与传统的源代码注释不同,docstring 应该描述函数做什么,而不是如何做。
所有函数都应该有一个 docstring。这允许程序在运行时检查这些注释,例如作为交互式帮助系统,或者作为元数据。
文档字符串可以通过对象的 doc 属性来访问。
Docstring 应该是什么样子?
文档字符串行应该以大写字母开始,以句点结束。第一行应该是简短的描述。
不要写对象的名字。如果文档字符串中有更多行,第二行应该是空白的,从视觉上将摘要与描述的其余部分分开。
下面几行应该是一个或多个段落,描述对象的调用约定,它的副作用等等。
Docstring 示例
让我们展示一个多行 docstring 的例子:
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
让我们看看打印出来后会是什么样子
>>> print my_function.__doc__
Do nothing, but document it.
No, really, it doesn't do anything.
文档字符串的声明
以下 python 文件显示了 Python 源文件中的文档字符串声明:
"""
Assuming this is file mymodule.py, then this string, being the
first statement in the file, will become the "mymodule" module's
docstring when the file is imported.
"""
class MyClass(object):
"""The class's docstring"""
def my_method(self):
"""The method's docstring"""
def my_function():
"""The function's docstring"""
如何访问文档字符串
下面是一个交互式会话,展示了如何访问文档字符串
>>> import mymodule
>>> help(mymodule)
假设这是文件 mymodule.py,那么在导入文件时,作为文件中第一条语句的这个字符串将成为 mymodule modules docstring。
>>> help(mymodule.MyClass)
The class's docstring
>>> help(mymodule.MyClass.my_method)
The method's docstring
>>> help(mymodule.my_function)
The function's docstring
更多阅读
- http://en.wikipedia.org/wiki/Docstring
- http://docs . python . org/2/tutorial/control flow . html # tut-doc strings
- http://onlamp.com/lpt/a/python/2001/05/17/docstrings.html
Python : Easy_Install 包管理器
原文:https://www.pythonforbeginners.com/basics/python-easy_install-package-manager
简易安装软件包管理器
This post will be the first in a series of "Python Packing Manager" posts.
To know which one you are going to use, can be hard, as there are a few
different ones to choose from.
Let's start out with Easy_Install.
简单安装
Distributes Python programs and libraries (based on the Python Eggs wrapper)
It's a python module (easy_install) that is bundled with setuptools.
It lets you automatically download, build, install, and manage Python packages.
Easy_Install looks in the Python Package Index (PyPI) for the desired packages
and uses the metadata there to download and install the package and its
dependencies.
It is also hosted itself on the PyPI.
蟒蛇蛋
A Python egg is a way of distributing Python packages.
"Eggs are to Pythons as Jars are to Java..."
For a great introduction about this, I suggest you head over to [this](http://mrtopf.de/blog/en/a-small-introduction-to-python-eggs/ "python_eggs") post
setuptools
setuptools is a collection of enhancements to the Python distutils that allow
you to more easily build and distribute Python packages, especially ones that
have dependencies on other packages.
简易安装用法
下载和安装软件包
For basic use of easy_install, you need only supply the filename or URL of a
source distribution or .egg file (Python Egg).
By default, packages are installed to the running Python installation's
site-packages directory.
简易安装示例
Install a package by name, searching PyPI for the latest version,
and automatically downloading, building, and installing it:
**>>easy_install SQLObject**
Install or upgrade a package by name and version by finding links on
a given "download page":
**>>easy_install -f http://pythonpaste.org/package_index.html SQLObject**
Download a source distribution from a specified URL, automatically
building and installing it:
**>>easy_install http://example.com/path/to/MyPackage-1.2.3.tgz**
Install an already-downloaded .egg file:
**>>easy_install /my_downloads/OtherPackage-3.2.1-py2.3.egg**
Upgrade an already-installed package to the latest version listed on
PyPI:
**>>easy_install --upgrade PyProtocols**
Install a source distribution that's already downloaded and extracted
in the current directory (New in 0.5a9):
**>>easy_install .**
升级软件包
You don't need to do anything special to upgrade a package
Just install the new version, either by requesting a specific version, e.g.:
**>>easy_install "SomePackage==2.0"**
If you're installing to a directory on PYTHONPATH, or a configured "site"
directory (and not using -m), installing a package automatically replaces
any previous version in the easy-install.pth file, so that Python will
import the most-recently installed version by default.
So, again, installing the newer version is the only upgrade step needed.
A version greater than the one you have now:
**>>easy_install "SomePackage>2.0"**
Using the upgrade flag, to find the latest available version on PyPI:
**>>easy_install --upgrade SomePackage**
Or by using a download page, direct download URL, or package filename:
**>>easy_install -f http://example.com/downloads ExamplePackage
>>easy_install http://example.com/downloads/ExamplePackage-2.0-py2.4.egg
>>easy_install my_downloads/ExamplePackage-2.0.tgz**
更改活动版本
If you've upgraded a package, but need to revert to a previously-installed
version, you can do so like this:
**>>easy_install PackageName==1.2.3**
(where 1.2.3 is replaced by the exact version number you wish to switch to.
If a package matching the requested name and version is not already installed in
a directory on sys.path, it will be located via PyPI and installed.)
To switch to the latest installed version of PackageName:
**>>easy_install PackageName**
This will activate the latest installed version!
卸载软件包
If you have replaced a package with another version, then you can just delete
the package(s) you don't need by deleting the PackageName-versioninfo.egg file
or directory (found in the installation directory).
If you want to delete the currently installed version of a package
(or all versions of a package), you should first run:
**>>easy_install -mxN PackageName**
This will ensure that Python doesn't continue to search for a package you're
planning to remove.
After you've done this, you can safely delete the .egg files or directories,
along with any scripts you wish to remove.
For more information on how to use easy_install:
[http://peak.telecommunity.com/DevCenter/EasyInstall](http://peak.telecommunity.com/DevCenter/EasyInstall "EasyInstall")
Python 中的错误和异常
原文:https://www.pythonforbeginners.com/error-handling/python-errors-and-exceptions
错误和异常
在 Python 中,有两种错误:语法错误和异常。这篇文章将描述这些错误是什么。即将发布的帖子将展示我们如何处理这些错误。
句法误差
先说语法错误,(也叫解析错误)。
解析器重复出错的行,并显示一个“箭头”,指向行中检测到错误的最早点。
错误是由箭头前的标记引起的(或者至少是在箭头前的标记处检测到的):在本例中,错误是在关键字 print 处检测到的,因为它前面缺少一个冒号('😂。
文件名和行号被打印出来,这样您就知道在输入来自脚本的情况下应该在哪里查找。
例子
语法错误的示例
>>> while True print 'Hello world'
File "", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
例外
Python 中的另一种错误是例外。
即使语句或表达式在语法上是正确的,当试图执行它时,也可能会导致错误。
在执行过程中检测到的错误称为异常。
异常有不同的类型,类型作为消息的一部分打印出来。
示例中的类型是 ZeroDivisionError、NameError 和 TypeError。
异常错误
异常错误的示例。
>>> 10 * (1/0)
Traceback (most recent call last):
File "", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
Python 中的文件处理备忘单
原文:https://www.pythonforbeginners.com/cheatsheet/python-file-handling
文件处理
Python 中的文件处理不需要导入模块。
文件对象
相反,我们可以使用内置对象“文件”。默认情况下,该对象提供了操作文件所需的基本函数和方法。在读取、追加或写入文件之前,首先必须使用 Python 的内置 open()函数。在这篇文章中,我将描述如何使用文件对象的不同方法。
打开()
open()函数用于打开我们系统中的文件,filename 是要打开的文件的名称。模式指示文件将如何打开:“r”表示读取,“w”表示写入,“a”表示追加。open 函数有两个参数,文件名和打开文件的模式。默认情况下,当只传递文件名时,open 函数以读取模式打开文件。
例子
这个小脚本将打开(hello.txt)并打印内容。这将把文件信息存储在文件对象“文件名”中。
filename = "hello.txt"
file = open(filename, "r")
for line in file:
print line,
阅读()
read 函数包含不同的方法,read()、readline()和 readlines()
read() #return one big string
readline #return one line at a time
read-lines #returns a list of lines
写()
此方法将一系列字符串写入文件。
write () #Used to write a fixed sequence of characters to a file
writelines() #writelines can write a list of strings.
追加()
append 函数用于追加到文件中,而不是覆盖它。要追加到现有文件,只需在追加模式(“a”)下打开文件:
关闭()
当您处理完一个文件时,使用 close()关闭它并释放被打开的文件占用的所有系统资源
文件处理示例
让我们展示一些例子
To open a text file, use:
fh = open("hello.txt", "r")
To read a text file, use:
fh = open("hello.txt","r")
print fh.read()
To read one line at a time, use:
fh = open("hello".txt", "r")
print fh.readline()
To read a list of lines use:
fh = open("hello.txt.", "r")
print fh.readlines()
To [write to a file](https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python), use:
fh = open("hello.txt","w")
write("Hello World")
fh.close()
To [write to a file](https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python), use:
fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]
fh.writelines(lines_of_text)
fh.close()
To append to file, use:
fh = open("Hello.txt", "a")
write("Hello World again")
fh.close()
To close a file, use
fh = open("hello.txt", "r")
print fh.read()
fh.close()
功能
原文:https://www.pythonforbeginners.com/basics/python-functions-cheat-sheet
Python 中的函数是什么?
函数是你可以调用的东西(可能有一些参数,你放在括号里的东西),它执行一个动作并返回值。
我为什么要使用函数?
- 将代码任务简化为简单的任务
- 可以更容易地在开发人员之间分割代码
- 消除重复代码
- 重用代码
- 获得良好的代码结构
- 更容易调试。
函数的规则是什么?
- Python 中的函数必须在使用前定义。
- 使用关键字“def ”,后跟函数名和括号()来创建函数。
- 函数必须被命名,并指定它有什么参数(如果有的话)。
- 一个函数可以使用多个实参,每个实参都响应函数中的一个参数。
- 一个函数可以使用多个实参,每个实参都响应函数中的一个参数。
- 关键字“def”是必需的,并且必须是小写字母。
- 名字可以是你喜欢的任何东西。
- 行尾必须以冒号(:)结尾
- 该函数通常以使用 return 返回值结束。
- 函数内部的代码必须缩进
- 调用时使用该函数。
参数(自变量)
参数(也称为自变量)是函数的输入。Python 语言中的所有参数(自变量)都是通过引用传递的。有一些不同类型的参数,其中两个是:
位置
位置参数没有关键字,首先被赋值。
关键字
关键字参数有关键字,在位置参数之后第二个赋值。当你调用一个函数时,你决定使用位置、关键字或者两者的混合。如果你愿意,你可以选择做所有的关键字。
打电话
函数、过程或函数的调用必须有括号。在括号之间,可以有一个或多个参数值,但也可以为空。
首先发生的是函数参数获得它们的值,然后继续函数中的其余代码。当一个函数值完成时,它将它返回给调用。
单参数函数调用:
正常=摄氏度至华氏度(摄氏度温度)
不带参数的函数调用:
x =输入()
带两个参数的过程调用:
矩形(20,10)
不带参数的过程调用:
说你好()
请记住,当 Python 进行调用时,必须已经定义了函数。
返回
参数是函数的输入,返回值是输出。
return 关键字用于从函数中返回值。该函数将根据 return 命令退出。(之后的所有代码都将被忽略)
函数可能会也可能不会返回值。如果函数没有 return 关键字,它将发送一个 None 值。
在 Python 中创建函数
在 Python 中创建一个函数的第一件事是定义它并给它一个名字(可能在括号中有一些参数)
定义它并给它一个名称> > def name()
为函数>>命令创建方向
调用函数> > name()
通过在定义中创建变量,可以向函数发送值。(这些变量只在这个特定的函数内部起作用)
让我们看一个例子:
第一行定义了函数号()
该函数有两个参数 num1 和 num2
第二行将 num1 和 num2 相加
def numbers(num1, num2):
print num1+num2
如果这个定义在程序的开始,我们要做的就是写 def 数字(1,2)来把值发送给函数。
我们通过在函数调用中赋值来实现。你也可以定义数学函数。这需要一个数的平方根:def square(x): return x*x
让我们看一个例子,如何创建一个简单的函数的任何参数。
def name():
# Get the user's name.
name = raw_input('Enter your name: ')
# Return the name.
return name
name()
在第二个示例中,显示了如何将参数传递给函数:
def even(number):
if number % 2 == 0:
return True
else:
return False
print even(10)
例子
如果你还没有读过 Python 的非程序员教程,读一读吧。这是学习 Python 的绝佳资源。
这个转换温度的例子是一个如何使用函数的好例子。
def print_options():
print "Options:"
print " 'p' print options"
print " 'c' convert from celsius"
print " 'f' convert from fahrenheit"
print " 'q' quit the program"
def celsius_to_fahrenheit(c_temp):
return 9.0 / 5.0 * c_temp + 32
def fahrenheit_to_celsius(f_temp):
return (f_temp - 32.0) * 5.0 / 9.0
choice = "p"
while choice != "q":
if choice == "c":
temp = input("Celsius temperature: ")
print "Fahrenheit:", celsius_to_fahrenheit(temp)
elif choice == "f":
temp = input("Fahrenheit temperature: ")
print "Celsius:", fahrenheit_to_celsius(temp)
elif choice != "q":
print_options()
choice = raw_input("option: ")
我希望你喜欢这个小抄,希望你今天学到了一些东西。
Python:猜谜游戏第 2 部分
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-guessing-game-part-2
概观
这个小程序扩展了我之前在这个
中写过的猜谜游戏:post“Python 猜谜游戏”。
猜谜
在这个游戏中,我们将添加一个计数器来计算用户可以猜多少次。
计数器初始设置为零。
只要猜测次数少于 5 次,while 循环就会运行。
如果用户在此之前猜中了正确的数字,脚本将会中断,并向用户显示猜对数字需要猜多少次。
该脚本中的变量可以更改为任何值。
为了便于阅读,我将把程序分成几块
首先,我们导入随机模块
import random
然后我们给“数字”变量一个 1 到 99 之间的随机数。
number = random.randint(1, 99)
将 guests 变量设置为 0,这将对猜测进行计数
guesses = 0
只要猜测的次数少于 5 次,就让用户猜一个数字。
然后将猜测计数器加 1。
打印出一条消息给用户猜测的次数。
while guesses < 5:
guess = int(raw_input("Enter an integer from 1 to 99: "))
guesses +=1
print "this is your %d guess" %guesses
检查猜测值是低于、高于还是等于我们的随机数,并打印结果消息
。
如果猜测和我们的数字一样,退出程序。
if guess < number:
print "guess is low"
elif guess > number:
print "guess is high"
elif guess == number:
break
打印出用户的猜测次数。
if guess == number:
guesses = str(guesses)
print "You guess it in : ", guesses + " guesses"
如果用户 5 次都猜不到正确的数字,打印出
密码是什么。
if guess != number:
number = str(number)
print "The secret number was", number
我希望你喜欢这个猜谜游戏。
Python 中猜谜游戏的实现
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-guessing-game
用 python 编写简单的游戏是练习条件语句和循环的好方法。在本文中,我们将使用 if-else 块和 while 循环在 python 中实现一个猜谜游戏。
猜谜游戏是什么?
我们要用 python 实现的猜谜游戏有简单的规则。
- 首先,程序生成一个介于 1 和 99 之间的随机数。
- 然后,它让用户猜这个数字。
- 如果用户输入的数字小于系统生成的数字,系统会告诉用户猜测值较低。然后,它要求用户再次猜测号码。
- 如果用户输入的数字大于系统生成的数字,系统告诉用户猜测的数字更大。然后,它要求用户再次猜测号码。
- 如果用户猜对了数字,系统通知用户,游戏结束。
如何用 Python 实现猜谜游戏?
我们将使用以下步骤来创建猜谜游戏。
- 首先,我们将使用 python 中的 random 模块中的 randint()函数来生成一个介于 1 和 99 之间的随机数。
- 接下来,我们将使用 input()函数将用户猜测的数字作为输入。
- 之后,我们将使用 while 循环来实现程序逻辑。在 while 循环中,我们将使用 if-else 块来检查用户输入的条件。
- 如果用户猜对了数字,我们将使用 break 语句来退出 while 循环并结束程序。
下面是用 Python 实现猜谜游戏的完整代码。
import random
n = random.randint(1, 99)
guess = int(input("Enter an integer from 1 to 99: "))
while True:
if guess < n:
print ("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("you guessed it right! Bye!")
break
输出:
Enter an integer from 1 to 99: 23
guess is low
Enter an integer from 1 to 99: 45
guess is low
Enter an integer from 1 to 99: 67
guess is low
Enter an integer from 1 to 99: 89
guess is low
Enter an integer from 1 to 99: 98
you guessed it right! Bye!
结论
在本文中,我们讨论了如何用 python 创建一个猜谜游戏。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中 hangman 游戏的文章。您可能也会喜欢这篇关于 Python 中的字符串操作的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python Idle:初学者指南
原文:https://www.pythonforbeginners.com/basics/python-idle-a-beginners-guide
如果您在这里,您最近已经在您的机器上安装了 python 或者您想要这样做。Python IDLE 是你学习 Python 的第一批软件之一。本文将讨论开始使用 Python IDLE 所需要了解的一切。
Python 空闲是什么?
当您在 Windows 或 Mac 上安装 python 时,安装会附带 IDLE。IDLE 代表集成开发和学习环境。看名字就能猜到,IDLE 帮助你入门学习 python。如果你是初学者,它可以成为你学习 python 最好的工具之一。
作为交互式 Python 解释器的 Python IDLE
IDLE 可以作为交互式解释器工作。您可以逐行编写 python 命令,它会执行这些命令并显示结果。您也可以将交互式 python 解释器称为 python shell。python shell 旨在读取 python 命令、评估语句、打印结果,并重复相同的过程,直到退出。
如果您想了解变量、赋值、数学和位运算,或者 python 中对列表和字符串等数据结构的运算,您可以使用 python IDLE 逐行执行语句。
如果需要,也可以在 python IDLE 中编写小块代码。但是,我会建议你使用 python 文件在 python 程序中编写代码块,然后执行它。
Python 空闲时作为文件编辑器
在编写函数或循环等代码块时,可以创建扩展名为. py 的 python 脚本文件。
所有 python 文件的扩展名都是. py。您可以使用一个 python 文件一次执行任意数量的语句。使用 Python IDLE,您可以非常容易地创建和修改现有的 Python 文件。
作为集成开发环境的 Python IDLE
集成开发环境(IDE)为您提供了不同的工具和功能,帮助您以简单的方式编写程序。Python IDLE 还提供了不同的特性,比如语法突出显示、自动缩进、代码完成、突出显示和代码重构。本文将讨论如何在 python IDLE 中使用所有这些特性。
如何安装 Python IDLE?
当您在 Windows 机器或 MacOS 上安装 python 时,python IDLE 与 Python 安装捆绑在一起。你不需要单独安装 IDLE。
在 Linux 机器上,您可以按照以下步骤使用 apt-get 安装 python IDLE。
首先,运行以下更新命令来更新存储库。
sudo apt-get update
这里,sudo 命令用于以超级用户的身份运行该语句,您需要有一个管理员密码来执行该命令。
在 update 语句之后,可以使用下面的语句安装 python idle。
sudo apt-get install idle
执行上述语句后,IDLE 将被安装在您的 Linux 机器上。您可以通过在搜索栏中搜索应用程序来验证这一点,如下所示。
IDLE Examples
或者,您可以在命令行终端中运行命令“idle”。执行该命令后,将启动 python IDLE。
IDLE Examples
在 Windows 机器上,你可以在开始菜单中搜索空闲,然后启动应用程序。
Python IDLE 入门
一旦您开始空闲,将出现以下屏幕。
Python IDLE Examples
在屏幕上,你可以看到下面的文字。
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
让我们输入“help
”,看看会发生什么。
IDLE Examples
程序建议输入“help()”。让我们这样做吧。
输入help()
后,出现以下画面。
IDLE Examples
在帮助菜单中,您可以键入任何内容来了解它在 python 中的含义。例如,让我们在帮助菜单中键入+号。执行后,将显示以下输出。
IDLE Examples
同样,当我们在帮助菜单中键入任何有效的文字时,相应的文档将会显示出来,以帮助您理解这些功能。
要从帮助菜单返回空闲编辑器窗口,您可以键入“ctrl+D
”。它会带你到主屏幕。
以类似的方式来帮助,你可以键入'copyright
'来查看谁拥有如下所示的闲置的版权。
IDLE Examples
您也可以通过在如下所示的空闲中键入'credits
'来查看演职员表。
IDLE Examples
了解了这些特性之后,现在让我们来讨论如何在 python IDLE 中执行不同的操作。
使用 IDLE 作为交互式 Python 解释器
可以使用 python IDLE 作为交互解释器,一条一条执行语句。您可以执行数学运算、比较、接受用户输入以及许多其他任务。让我们讨论其中的一些。
空闲时的数学运算
你可以像在计算器中一样将两个数相加。要执行任何数学运算,你只需要输入数学表达式,然后按回车键。解释器将显示输出。您可以在下图中观察到这一点。
IDLE Examples
这里,我们进行了各种数学运算。您可以观察到,当我们在输入一个表达式后按 enter 键时,输出会立即显示在 IDLE 中的下一行。
空闲时的比较操作
您还可以使用比较运算符来比较空闲。如果表达式计算结果为True
,解释器将打印True
。否则,将显示False
。
您还可以结合数学表达式和比较运算符来生成输出。
IDLE Examples
对空闲变量的操作
除了直接对数字执行运算,您还可以定义变量来存储值。
python 中的变量可以用来存储任何数字、字符串或其他数据类型。例如,您可以定义两个值分别为 10 和 20 的变量num1
和num2
,如下所示。
IDLE Examples
只需在如下所示的提示符下键入变量名,就可以打印变量中的值。
IDLE Examples
现在,您可以使用num1
和num2
将 10 和 20 相加,如下所示。
IDLE Examples
你也可以将num1
和num2
的和赋给另一个变量,如下所示。
IDLE Examples
这里,我们将num1
和num2
的和赋给了num3
。然后,我们打印出num3
中的值。
空闲时打印语句
除了数值之外,您还可以为变量分配文本值。在 python 中,文本被存储为一个字符串。为了定义字符串变量,我们将文本用单引号或双引号括起来,如下图所示。
IDLE Examples
这里,我们创建了一个名为website
的变量,并为其赋值为“Pythonforbeginners
”。您可以通过在如上所示的提示中键入变量名来打印变量中的值。
您可以使用print()
函数打印任何值,而不是直接在提示中键入变量名。print()
函数将一个值或变量作为其输入参数,并在终端中打印出来,如下所示。
IDLE Examples
您也可以通过在如下所示的print()
函数中用逗号分隔来打印多个值。
IDLE Examples
这里,值由空格字符分隔。
通过使用print()
函数中的sep
参数,可以使用逗号分隔 print 语句中的值。sep
参数将一个字符或字符串作为输入参数,并使用该字符分隔传递给print()
函数的值,如下所示。
IDLE Examples
在空闲时接受用户输入
您也可以使用input()
功能从用户处获取用户输入。input()
函数将代表用户提示的字符串作为其输入参数。执行时,它接受用户输入,直到用户按下 enter 键。一旦用户按下回车键,input()
函数就会以字符串的形式返回用户输入的所有字符。您可以在下面的示例中观察到这一点。
IDLE Examples
在上图中,我们首先使用input()
函数获取用户输入。我们还提示用户输入他的名字。一旦用户输入值,该值就被分配给变量名。然后,我们打印了存储在变量名中的值。
使用 Python IDLE 作为文件编辑器
要一次执行多条语句,需要在扩展名为. py 的文件中创建一个 python 脚本。
要创建一个 python 文件,可以从 IDLE 右上角的File
菜单中选择New File
选项。或者,你可以键入Ctrl+N
打开一个新的无标题文件。
创建无标题文件后,将出现以下屏幕。
IDLE Examples
您可以编写如下所示的代码。
IDLE Examples
在上面的代码中,程序要求用户输入他的姓名和年龄。之后,它计算用户的出生年份并打印结果。
input()
函数总是返回一个字符串值。因此,我们在第四行代码中使用了 int()
函数,将输入的年龄转换为整数。
在最后一个 print 语句中,我们使用了str()
函数将整数转换成字符串,这样解释器就可以执行字符串连接并打印结果。
编写完代码后,您需要运行 python 脚本。为此,首先需要用. py 扩展名保存文件。您可以进入File-> Save
选项,通过给出文件名来保存文件。之后,你可以点击Run-> Run Module
来运行你的 python 脚本。
点击Run module
,程序将在空闲状态下执行,输出如下图所示。
IDLE Examples
Python 空闲时的其他操作
- 没有办法清除空闲的终端。您需要关闭 IDLE 并重新启动它来清除屏幕。
- 您可以通过点击
Options-> Configure IDLE
并选择首选功能来更改字体、缩进宽度、高亮显示首选项、快捷键和其他功能。 - 点击
Help-> Python Docs
可以阅读 python 官方文档。当您点击 python 文档按钮时,您将被重定向到安装在您计算机上的 Python 版本的官方文档。 - 要在程序完成前停止执行,可以键入 ctrl+C。
- 要关闭 python IDLE,可以在键盘上键入
ctrl+D
。
结论
在本文中,我们讨论了有助于您开始使用 python IDLE 的各种操作。想要了解更多关于 python 编程的知识,你可以注册这个 python 初学者课程。
Python If…Elif…Else 语句
原文:https://www.pythonforbeginners.com/basics/python-if-elif-else-statement
什么是条件?
Conditions tests if a something is True or False, and it uses Boolean values
(type bool) to check that.
You see that conditions are either True or False (with no quotes!).
2 < 5
3 > 7
x = 11
x > 10
2 * x < x
type(True)
The results of these tests decides what happens next.
何时使用条件?
If you want to check if the user typed in the right word or to see if a number is higher / lower than 100.
语法解释
First, lets look at Pythons if statement code block.
Rememeber, to indicate a block of code in Python, you must indent each line of the block by the same amount.
If ...else
if condition:
statements
elif condition:
statements
else:
statements
If, elif and else are keywords in Python.
A condition is a test for something ( is x less than y, is x == y etc. )
The colon (😃 at the end of the if line is required.
Statements are instructions to follow if the condition is true.
These statements must be indented and is only being run when the if condition
is met.
Typical conditions are: x<y, x>y, x<=y, x>=y, x!=y and x==y.
If you want more choices, you will have to include at least two conditions .
The "else" MUST be preceded by an if test and will ONLY run when condition of
the if statement is NOT met.
else will run if all others fail.
If you only have two choices in your construction, use if ..else
If there are more than two options, use if ..elif ..else.. that will make
it easier to read
elif is short for "else if"
条件测试
An If statement sets an condition with one or more if statement that will be
used when a condition is met.
There can be zero or more elif parts, and the else part is optional.
The keyword 'elif' is short for 'else if', and is useful to avoid excessive
indentation.
An if ... elif ... elif ... sequence is a substitute for the switch or case
statements found in other languages.
x = raw_input("What is the time?")
if x < 10:
print "Good morning"
elif x<12:
print "Soon time for lunch"
elif x<18:
print "Good day"
elif x<22:
print "Good evening"
else:
print "Good night"
You can also use it to control that only specified users can login to a system.
# Allowed users to login
allowed_users = ['bill', 'steve']
# Get the username from a prompt
username = raw_input("What is your login? : ")
# Control if the user belongs to allowed_users
if username in allowed_users:
print "Access granted"
else:
print "Access denied"
Python If 语句代码块
To get an easy overview of Pythons if statement code block
if :
[do something]
....
....
elif [another statement is true]:
[do something else]
....
....
else:
[do another thing]
....
....
For more reading, please see Python's official documentation.
如何在 Python 中导入模块
原文:https://www.pythonforbeginners.com/basics/python-importing-modules
模块
Python 模块使得编程更加容易。
它基本上是一个由已经编写好代码组成的文件。
当 Python 导入一个模块时,它首先检查模块注册表(sys.modules)
以查看该模块是否已经被导入。
如果是这种情况,Python 将使用现有的模块对象。
导入模块
导入模块有不同的方法
import sys
# access module, after this you can use sys.name to refer to
# things defined in module sys.
from sys import stdout
# access module without qualifying name.
# This reads >> from the module "sys" import "stdout", so that
# we would be able to refer "stdout" in our program.
from sys import *
# access all functions/classes in the sys module.
使用 Python 解释器
原文:https://www.pythonforbeginners.com/basics/python-interpreter
Python 解释器
Python 解释器通常安装在机器
上的/usr/local/bin/python 中;
将/usr/local/bin 放在您的 Unix shell 的搜索路径中,可以通过在 shell 中键入命令:python 来启动它。
当您以交互模式启动 Python 时,它会提示输入下一个命令,
通常是三个大于号(> > >)。
解释器在打印第一个提示之前打印一条欢迎消息,说明其版本号和一个
版权声明,例如:
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Python 交互式
当您交互式地使用 Python 时,每次启动解释器时执行一些标准命令
会很方便。
您可以通过将名为 PYTHONSTARTUP 的环境变量设置为包含启动命令的文件的名称
来实现这一点。
这类似于。Unix shells 的概要特性。
为此,请将这一行添加到您的。bashrc 文件:
导出 PYTHONSTARTUP=$HOME/。pythonstartup
创建(或修改)的。pythonstartup 文件,并将您的 python 代码放在那里:
import os
os.system('ls -l')
要退出 Python 交互式提示符,我们将按 Ctrl+D(在 Linux 中)
更多信息见 Pythons 官方文档。
Python 连接示例
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-join-examples
概观
这篇文章将展示 Python join 方法的一些例子。
重要的是要记住,连接元素
的字符是调用函数的字符。
加入示例
让我们展示一个例子
创建新列表
>>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"]
>>> print music
['Abba', 'Rolling Stones', 'Black Sabbath', 'Metallica']
用空格连接列表
>>> print ' '.join(music)
Abba Rolling Stones Black Sabbath Metallica
用新行加入列表
>>> print "
".join(music)
Abba
Rolling Stones
Black Sabbath
Metallica
用选项卡加入列表
>>> print " ".join(music)
Abba Rolling Stones Black Sabbath Metallica
>>>
快乐脚本!
Python KeyError
原文:https://www.pythonforbeginners.com/basics/python-keyerror
在 python 中使用字典时,您可能会遇到 KeyError。在本文中,我们将讨论什么是 KeyError,它是如何发生的,以及如何在使用 python 字典时避免 KeyError。
什么是 Python KeyError?
简而言之,当我们试图用字典中不存在的键访问字典中的值时,KeyError 是 python 程序引发的异常。
例如,看看下面的程序。这里,字典 myDict 具有键 1、2 和 3,值 1、4 和 9 与这些键相关联。当我们试图用键 4 访问字典时,程序会引发一个 KeyError。这是因为 4 在字典中不是一个键。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
print(myDict[4])
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string.py", line 3, in <module>
print(myDict[4])
KeyError: 4
如何避免 Python KeyError 异常?
有多种方法可以避免 KeyError 异常。让我们逐一讨论。
使用 If else 语句
使用 if else 语句,我们可以在访问值之前检查给定的键是否存在于字典的键中。这有助于我们避免 KeyError 异常。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
if key in myDict.keys():
print(myDict[key])
else:
print("{} not a key of dictionary".format(key))
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
4 not a key of dictionary
这里的缺点是,每次我们都必须检查给定的键是否存在于字典的键中。如果我们使用 get()方法从字典中访问值,就可以避免这些额外的工作。
使用 get()方法
当在字典上调用 get()方法时,它将给定的键和一个可选值作为输入。如果给定的键存在于字典中,它会将相关的值作为输出提供给该键,如下所示。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 3
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 3
Value associated to the key is: 9
当给定的键不在字典中时,如果没有传递可选值,它将返回 None。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: None
如果我们将一个可选值作为输入传递给 get()方法,当给定的键不在字典中时,它将返回该值。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key,16))
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: 16
使用 Try Except
我们可以使用 python try except 块来处理 KeyError 异常。为此,我们将执行代码,使用 try 块中的给定键来访问值,并将处理 except 块中的异常,如下所示。
myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key=4
print("Key is:",key)
try:
val=myDict[key]
print("Value associated to the key is:",val)
except KeyError:
print("Key not present in Dictionary")
输出:
The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Key not present in Dictionary
结论
在本文中,我们讨论了键错误以及处理它们的方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python:列举例子
原文:https://www.pythonforbeginners.com/basics/python-list-examples
什么是列表?
请记住,列表是用方括号[ ]创建的,元素必须在方括号内。
列表中的元素不必是同一类型(可以是数字、字母、字符串)。
在这个例子中,我们将创建一个只包含数字的列表。
列表示例
创建列表
myList = [1,2,3,5,8,2,5.2]
i = 0
while i < len(myList):
print myList[i]
i = i + 1
这是做什么的?
这个脚本将创建一个包含值 1,2,3,5,8,2,5.2 的列表(list1)
while 循环将打印列表中的每个元素。
list1 中的每个元素都是通过索引(方括号中的字母)到达的。
len 函数用于获取列表的长度。
然后,每当 while 循环运行一次,我们就将变量 I 增加 1。
输出
Output >> 1 2 3 5 8 2 5.2
例子
下一个例子将计算列表中元素的平均值。
list1 = [1,2,3,5,8,2,5.2]
total = 0
i = 0
while i < len(list1):
total = total + list1[i]
i = i + 1
average = total / len(list1)
print average
#Output >> 3.74285714286
Python 中的列表操作
原文:https://www.pythonforbeginners.com/basics/python-list-manipulation
概观
List 是 Python 中最简单也是最重要的数据结构之一。
列表用方括号[ ]括起来,每个项目用逗号分隔。
列表是项目的集合,其中列表中的每个项目都有一个分配的索引值。
列表是可变的,意味着你可以改变它的内容。
列表非常灵活,有许多内置的控制功能。
列表对象的方法
对列表方法的调用使它们操作的列表出现在方法名之前,用点分隔,例如 L.reverse()
Creation
L = ['yellow', 'red', 'blue', 'green', 'black']
>>>print L
returns: ['yellow', 'red', 'blue', 'green', 'black']
##########
Accessing / Indexing
L[0] = returns 'yellow'
##########
Slicing
L[1:4] = returns ['red', 'blue', 'green']
L[2:] = returns ['blue', 'green', 'black']
L[:2] = returns ['yellow', 'red']
L[-1] = returns 'black'
L[1:-1] = returns ['red', 'blue', 'green']
##########
Length - number of items in list
len(L) = returns 5
##########
Sorting - sorting the list
sorted(L) = returns ['black', 'blue', 'green', 'red', 'yellow']
##########
Append - append to end of list
L.append("pink")
>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']
##########
Insert - insert into list
L.insert(0, "white")
>>> print L
returns: ['white', 'black', 'blue', 'green', 'red', 'yellow', 'pink']
##########
Extend - grow list
L.extend(L2)
##########
Remove - remove first item in list with value "white"
L.remove("white")
>>> print L
returns: ['black', 'blue', 'green', 'red', 'yellow', 'pink']
##########
Delete
Remove an item from a list given its index instead of its value
del.L[0]
>>> print L
['blue', 'green', 'red', 'yellow', 'pink']
##########
Pop
Remove last item in the list
L.pop() = returns 'pink'
# remove indexed value from list
L.pop(1) = returns 'green'
##########
Reverse - reversing the list
L.reverse()
##########
Count
Search list and return number of instances found
L.count('red')
##########
Keyword "in" - can be used to test if an item is in a list
if 'red' in L:
print "list contains", 'red'
##########
For-in statement - makes it easy to loop over the items in a list
for item in L:
print item
L = ['red', 'blue', 'green']
for col in L:
print col
Python:列出方法
原文:https://www.pythonforbeginners.com/basics/python-list-methods
就像字符串方法一样,列表方法作用于调用它的列表,例如,如果你有一个名为 list1 = ["Movies "," Music "," Pictures"]的列表,那么列表方法就这样调用:list1.list_method()让我们通过在 python 解释器中键入一些列表方法来演示这一点。
>>> list1 = ["Movies", "Music", "Pictures"]
#list1.append(x) will add an element to the end of the list
>>> list1.append("Files")
>>> list1
['Movies', 'Music', 'Pictures', 'Files']
#list1.insert(x, y) will add element y on the place before x
>>> list1.insert(2,"Documents")
>>> list1
['Movies', 'Music', 'Documents', 'Pictures', 'Files']
#list1.remove(x) will remove the element x from the list
>>> list1.remove("Files")
>>> list1
['Movies', 'Music', 'Documents', 'Pictures']
#list1.extend(x) will join the list with list x
>>> list2 = ["Music2", "Movies2"]
>>> list1.extend(list2)
>>> list1
['Movies', 'Music', 'Documents', 'Pictures', 'Music2', 'Movies2']
请看这个列表方法帖子,它描述了更多的列表方法
Python 列表备忘单
原文:https://www.pythonforbeginners.com/lists/python-lists-cheat-sheet-2
什么是列表?
Python 列表用于存储数据集合。Python 可以将多个值赋给一个列表,这在处理大量数据时非常方便。
列表可以保存任何类型的数据,包括整数、字符串,甚至其他列表。列表是动态的,可以更改。使用特殊的方法,我们可以在 Python 列表中添加或删除项目。
列表中的元素是有索引的,每个元素在列表的顺序中都有明确的位置。与 Python 字符串不同,列表的内容是可以改变的。
列表创建
Python 列表是用方括号写的。列表中的元素用逗号分隔。稍后,我们将看到如何添加和删除元素。
# a list for days of the work week
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
# an empty list just waiting to do something
empty_list = []
# lists can hold data of different types
mix_list = ["one","two",1,2]
查找列表的长度
使用 len() 方法计算列表的长度。这个方法将返回列表中元素的总数。
nums = [0,1,2,3,4,5,6,7,8,9]
# print the total number of items in the list
print("Length of the list: ", len(nums))
输出
Length of the list: 10
追加列表
我们可以使用 append() 方法向列表中添加条目。新元素将出现在列表的末尾。
# a list of popular car manufacturers
car_brands = ["BMW","Ford","Toyota","GM","Honda","Chevrolet"]
# add to a list with append()
car_brands.append("Tesla")
列表插入
在上面的例子中,我们看到我们可以将项目添加到列表的末尾。如果我们想把一些东西放在开头,甚至中间呢?
用 insert() 方法,我们可以指定在列表中的什么地方添加一个新元素。
letters = ['B','C','D','E','F','G']
letters.insert(0,'A') # add element 'A' at the first index
print(letters)
输出
['A', 'B', 'C', 'D', 'E', 'F', 'G']
列表插入语法:
my_list.insert(x,y) # this will insert y before x
# an example of inserting an element into the third position in a list
top_five = ["The Beatles","Marvin Gaye","Gorillaz","Cat Power"]
top_five.insert(2, "Prince")
print(top_five)
输出
['The Beatles', 'Marvin Gaye', 'Prince', 'Nirvana', 'Cat Power']
从列表中删除元素
从列表中删除一个元素,使用 remove() 方法。这个方法将找到列表中第一个出现的条目并删除它。
# a basic to do list
to_do = ["dishes","laundry","dusting","feed the dog"]
# we already fed Fido!
to_do.remove("feed the dog")
print("Things to do: ", to_do)
# remove the first 3 in the list
nums = [1,2,3,3,4,5]
nums.remove(3)
print(nums)
输出
Things to do: ['dishes', 'laundry', 'dusting']
[1, 2, 3, 4, 5]
建议阅读:如何用 Python 制作聊天 app?
扩展列表
Python 提供了一种用 extend() 方法连接列表的方法。使用这种方法,一个列表的元素将被添加到另一个列表的末端。
# we need a list of items to send to the movers
furniture = ["bed","chair","bookcase"]
# add additional elements with extend()
furniture.extend(["couch","desk","coffee table"])
print(furniture)
输出
['bed', 'chair', 'bookcase', 'couch', 'desk', 'coffee table']
使用 pop()删除元素
除了 remove(),我们还可以使用 pop() 方法从列表中移除元素。使用 pop()方法移除特定索引处的元素。
nums = [1,2,3,4]
nums.pop(1)
print(nums)
输出
[1, 3, 4]
位于索引 1 的元素已被移除。如果我们不向 pop()传递索引,它将从列表中删除最后一项。
# generate a list of numbers 1-10
nums = [x for x in range(1,11)]
# pop the last element off the list
nums.pop()
print(nums)
输出
[1, 2, 3, 4, 5, 6, 7, 8, 9]
关键词
在处理列表时,有几个 Python 关键字很方便。关键字中的可以用来检查一个项目是否在列表中。
在中使用的语法如下:
list_item in list
下面是一个使用关键字中的来确定列表是否包含特定字符串的示例:
the_beatles = ["John","Paul","George","Ringo"]
print("Was John in the Beatles? ","John" in the_beatles)
输出
Was John in the Beatles? True
另一个有用的关键词是不是。通过使用 not,我们可以确定字符串中是否缺少某个元素。
print("So Yoko wasn't a member of the Beatles? ","Yoko" not in the_beatles)
输出
So Yoko wasn't a member of the Beatles? True
反转列表
在 Python 中反转列表最简单的方法是使用 reverse() 方法。该方法对列表进行重新排序,使最后一个元素成为第一个元素,反之亦然。
或者,我们可以使用 Python 切片符号反向遍历列表。
superheroes = ["Batman", "The Black Panther", "Iron Man"]
# use slice notation to traverse the list in reverse
for hero_name in superheroes[::-1]:
print(hero_name)
# use the reverse method to reverse a list in place
superheroes.reverse()
print(superheroes)
输出
Iron Man
The Black Panther
Batman
['Iron Man', 'The Black Panther', 'Batman']
列表排序
使用 Python 的 sort() 方法对列表中的元素重新排序。默认情况下,sort()将重新排列列表,以便它包含的项目按升序排列。例如,对数字列表使用 sort 会将数字从最小到最大排序。
nums = [100,2003,1997,3,-9,1]
nums.sort()
print(nums)
输出
[-9, 1, 3, 100, 1997, 2003]
或者,在字符串上使用 sort()将把项目按字母顺序排列。
alphabet = ['B','C','A']
alphabet.sort()
print(alphabet)
输出
['A', 'B', 'C']
如果需要保持原来的列表不变,选择 sorted() 方法。sorted()方法返回一个新的列表,保持原来的列表不变。
nums = [7,2,42,99,77]
# sorted will return a new list
print("Modified list:", sorted(nums))
print("Original list: ", nums)
输出
Modified list: [2, 7, 42, 77, 99]
Original list: [7, 2, 42, 99, 77]
列表索引
使用索引来引用列表中的项目。索引代表项目在列表中出现的顺序。
列表中的第一项位于索引 0 处。第二个在索引 1,依此类推。
villains = ["Shredder","Darth Vader","The Joker"]
print(villains[0])
print(villains[1])
print(villains[2])
输出
Shredder
Darth Vader
The Joker
与 Python 字符串不同,列表是可以改变的。例如,我们可以使用 Python 来交换列表中第一项和第三项的内容。
# swamp the first and third items of the list
temp = villains[2]
villains[2] = villains[0]
villains[0] = temp
然而,有一种更简单的方法来淹没 Python 中的列表项。
# swap list items with the power of Python!
villains[0],villains[2]=villains[2],villains[0]
限幅
Python 切片允许我们从一个列表中检索多个项目。切片的符号是期望范围的开始和结束之间的冒号。
语法:
my_list[start:end:step]
对于一个给定的列表,切片符号查找起始索引和结束索引。这告诉 Python 我们要寻找的项目的范围。
可选地,我们可以指定遍历列表的步骤。该步骤告诉 Python 如何遍历列表。例如,我们可以提供一个负数来反向遍历列表。
rainbow = ['red','orange','yellow','green','blue','indigo','violet']
print(rainbow[1]) # get the second item in the list
print(rainbow[:1]) # get items at indexes 0 and 1
print(rainbow[1:3]) # items at index 1 and 2
print(rainbow[:-1]) # all items excluding the last
输出
orange
['red']
['orange', 'yellow']
['red', 'orange', 'yellow', 'green', 'blue', 'indigo']
循环和列表
因为 Python 中的列表是有索引的,所以我们可以使用循环来遍历它们的元素。
# a list of random numbers in ascending order
nums = [2,4,7,8,9,10,11,12,13,15,16,17]
# a list of prime numbers
primes = [2,3,5,7,11,13,17]
# loop through a Python list
for num in nums:
if num in primes:
print(num,end=" ")
输出
2 7 11 13 17
列出方法
我们已经看到了 Python 列表方法的例子,比如 reverse()和 sort()。不幸的是,这篇文章没有足够的篇幅来涵盖它们,但是我们提供了一个您应该知道的列表,并描述了它们的作用。
- Append(): 在列表末尾添加一个新项目。
- Count() :返回列表中项目的总数。
- Clear(): 从列表中删除所有项目。
- Extend(): 将一个列表的元素连接到另一个列表的末尾。
- Index(): 查找列表中某项的索引。
- 将一个条目添加到列表中给定的索引处。
- 从列表中删除最后一项。
- 从列表中删除一个特定的项目。
- Reverse(): 从最后一项到第一项对列表进行重新排序。
- Sort(): 对列表进行升序排序。
例子
让我们以一些在 Python 中使用列表和列表方法的例子来结束本文。
示例 1:计算数字列表中所有项目的总和
nums = [98,62,77,84,89]
total = 0
for i in range(len(nums)):
total += nums[i]
print("Total: ", total)
输出
Total: 410
示例 2:计算一组数字的平均值
# find the average for a list of numbers
nums = [20,22,1.5,2,7,5.2,99]
total = 0
i = 0
while i < len(nums):
total = total + nums[i]
i = i + 1
average = total/len(nums)
print("The average to 2 decimal places: {:.2f}".format(average))
输出
The average to 2 decimal places: 22.39
相关职位
列表
原文:https://www.pythonforbeginners.com/basics/python-lists-cheat-sheet
什么是列表?
Python 中最简单的数据结构,用于存储值列表。
列表是项目的集合(字符串、整数甚至其他列表)。
列表中的每个项目都有一个指定的索引值。
列表括在[ ]中
列表中的每一项都用逗号分隔
与字符串不同,列表是可变的,这意味着它们可以被改变。
列表创建
列表是使用由方括号
包围的逗号分隔的值列表创建的。
列表保存一个值序列(就像字符串可以保存一个字符序列
)。
列表很容易创建,这是制作列表的一些方法
emptyList = [ ]
list1 = ['one, two, three, four, five']
numlist = [1, 3, 5, 7, 9]
mixlist = ['yellow', 'red', 'blue', 'green', 'black']
#An empty list is created using just square brackets:
list = []
列表长度
使用 length 函数,我们可以得到一个列表的长度
list = ["1", "hello", 2, "world"]
len(list)
>>4
列表追加
列表追加将在末尾添加项目。
如果想在开头添加,可以使用插入功能(见下文)
list.insert(0, "Files")
list = ["Movies", "Music", "Pictures"]
list.append(x) #will add an element to the end of the list
list.append("Files")
print list
['Movies', 'Music', 'Pictures', 'Files’]
列表插入
语法是:
list.insert(x, y) #will add element y on the place before x
list = ["Movies", "Music", "Pictures"]
list.insert(2,"Documents")
print list
['Movies', 'Music', 'Documents', 'Pictures', 'Files']
#You can insert a value anywhere in the list
list = ["Movies", "Music", "Pictures"]
list.insert(3, "Apps”)
列表删除
要删除列表中的第一个元素,只需使用 list.remove
语法是:
list.remove(x)
List = ['Movies', 'Music', 'Files', 'Documents', 'Pictures']
list.remove("Files")
print list
['Movies', 'Music', 'Documents', 'Pictures']
a = [1, 2, 3, 4]
a.remove(2)
print a
[1, 3, 4]
列表扩展
语法是:
list.extend(x) #will join the list with list x
list2 = ["Music2", "Movies2"]
list1.extend(list2)
print list1
['Movies', 'Music', 'Documents', 'Pictures', 'Music2', 'Movies2’]
列表删除
使用 del 删除基于索引位置的项目。
list = ["Matthew", "Mark", "Luke", "John"]
del list[1]
print list
>>>Matthew, Luke, John
列出关键词
关键字“in”可用于测试一个项目是否在列表中。
list = ["red", "orange", "green", "blue"]
if "red" in list:
do_something()
#Keyword "not" can be combined with "in".
list = ["red", "orange", "green", "blue"]
if "purple" not in list:
do_something()
反向列表
reverse 方法反转整个列表的顺序。
L1 = ["One", "two", "three", "four", "five"]
#To print the list as it is, simply do:
print L1
#To print a reverse list, do:
for i in L1[::-1]:
print i
#OR
L = [0, 10, 20, 40]
L.reverse()
print L
[40, 20, 10, 0]
列表排序
对列表排序最简单的方法是使用 sorted(list)函数。
它接受一个列表并返回一个新列表,其中的元素按排序顺序排列。
原始列表不变。
sorted()函数可以通过可选参数定制。
sorted()可选参数 reverse=True,例如 sorted(list,reverse=True),
使其向后排序。
#create a list with some numbers in it
numbers = [5, 1, 4, 3, 2, 6, 7, 9]
#prints the numbers sorted
print sorted(numbers)
#the original list of numbers are not changed
print numbers
my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "EE"]
#if no argument is used, it will use the default (case sensitive)
print sorted(my_string)
#using the reverse argument, will print the list reversed
print sorted(strs, reverse=True) ## ['zz', 'aa', 'CC', 'BB']
This will not return a value, it will modify the list
list.sort()
列表拆分
拆分列表中的每个元素。
mylist = ['one', 'two', 'three', 'four', 'five']
newlist = mylist.split(',')
print newlist
['one', ' two', ' three', ' four', 'five’]
列表索引
列表中的每个项目都有一个从 0 开始的指定索引值。
访问列表中的元素称为索引。
list = ["first", "second", "third"]
list[0] == "first"
list[1] == "second"
list[2] == "third”
列表切片
访问部分数据段称为切片。
通过使用[ ]操作符,可以像访问字符串一样访问列表。
要记住的关键点是:end 值代表第一个值,即
不在所选切片中。
因此,结束和开始之间的差异是所选元素的数量
(如果步长为 1,则为默认值)。
让我们创建一个包含一些值的列表
colors = ['yellow', 'red', 'blue', 'green', 'black']
print colors[0]
>>> yellow
print colors [1:]
>>> red, blue, green, black
让我们来看看这个取自这篇 stackoverflow 帖子的例子。
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
还有一个步长值,可以与上述任何一个一起使用
a[start:end:step] # start through not past end, by step
另一个特性是 start 或 end 可能是负数,这意味着它从数组的结尾而不是开头开始计数
。
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
列表循环
在编程中使用循环时,有时需要存储
循环的结果。
在 Python 中做到这一点的一种方法是使用列表。
这一小段将展示如何使用一个 Python for 循环来迭代列表并处理
列表项。
#It can look something like this:
matching = []
for term in mylist:
do something
#For example, you can add an if statement in the loop, and add the item to the (empty) list
if it's matching.
matching = [] #creates an empty list using empty square brackets []
for term in mylist:
if test(term):
matching.append(term)
#If you already have items in a list, you can easily loop through them like this:
items = [ 1, 2, 3, 4, 5 ]
for i in items:
print i
列出方法
对列表方法的调用使它们所操作的列表出现在方法名之前。
该方法完成工作所需的任何其他值都以正常方式提供,作为圆括号内的一个额外参数。
s = ['h','e','l','l','o'] #create a list
s.append('d') #append to end of list
len(s) #number of items in list
s.sort() #sorting the list
s.reverse() #reversing the list
s.extend(['w','o']) #grow list
s.insert(1,2) #insert into list
s.remove('d') #remove first item in list with value e
s.pop() #remove last item in the list
s.pop(1) #remove indexed value from list
s.count('o') #search list and return number of instances found
s = range(0,10) #create a list over range
s = range(0,10,2) #same as above, with start index and increment
列举例子
让我们以展示一些列表示例来结束这篇文章:首先,创建一个只包含数字的列表。
list = [1,2,3,5,8,2,5.2] #creates a list containing the values 1,2,3,5,8,2,5.2
i = 0
while i < len(list): #The while loop will print each element in the list
print list[i] #Each element is reached by the index (the letter in the square bracket)
i = i + 1 #Increase the variable i with 1 for every time the while loop runs.
下一个例子将计算列表中元素的平均值。
list = [1,2,3,5,8,2,5.2]
total = 0
i = 0
while i < len(list):
total = total + list[i]
i = i + 1
average = total / len(list)
print average
相关职位
Python 文字
原文:https://www.pythonforbeginners.com/basics/python-literals
在阅读 python 编程材料时,您一定遇到过某些短语,如关键字、变量、常量和文字。在本文中,我们将研究 python 中文字的定义和用法的基本概念。
什么是 Python 文字?
文字是编程时赋给变量或常量的原始数据。在 python 中,我们有不同类型的文字,如字符串文字、数字文字、布尔文字和特殊文字 None。在接下来的章节中,我们将研究每种类型的 python 文字,还将研究文字集合。
Python 中的字符串文字是什么?
字符串是用单引号、双引号或三引号括起来的字符序列。在 python 中,我们有两种类型的字符串,即单行字符串和多行字符串。
单行字符串是遇到换行符时终止的字符串文字。它可以通过在单引号或双引号中包含一个或多个字符来定义,如下所示。
myString="This is a single line string"
anotherString='This is also a single line string'
多行字符串可以通过用三重引号将扩展为多行的字符括起来来定义,如下所示。
myString="""This is
a
multiline string.
"""
什么是数字文字?
数字文字用于表示程序中的数字。在 python 中,我们有不同类型的数值,比如整数、浮点数和复数。
python 中的整数是没有小数部分的数字。表示十进制数的整数可以定义如下。
myNum=1117
我们也可以定义其他数系的整数。二进制数表示为以“0b”开头的数字文字,由数字 0 和 1 组成,如下所示。
myNum=0b10101
十六进制数字系统中的数字以“0x”开头,可以用 python 表示如下。
myNum=0x123ab
八进制数字系统中的整数文字以“0o”开头,可以用 python 表示如下。
myNum=0o124
python 中的浮点文字表示由整数和小数组成的实数。十进制数字系统中的浮点数可以表示如下。
myNum=123.345
复数的形式是 a+bj,其中“a”代表复数的实部,“b”代表复数的虚部。表示复数的数字文字可以写成如下形式。
myNum=3+4j
什么是布尔文字?
在 python 中,有两种类型的布尔文字,即 True 和 False。它们可以在程序中定义如下。
myVar=True
myVar1=False
特殊文字–无
文字“None”用于指定它所赋给的变量不引用任何对象。值为“无”的变量可定义如下。
myObj=None
Python 中的文字集合
有不同类型的集合对象,如 python 字典、列表、集合和元组,我们可以在其中存储 python 文本。
我们可以在 python 列表中存储不同类型的数据,如下所示。
myList=[1,2,"pfb",3.14]
我们甚至可以使用 python string split 操作在空格处断开字符串文字,并将子字符串保存在一个列表中,如下所示。
myStr="I am a single line string"
myList=myStr.split()
print("String literal is:",myStr)
print("Created list is:",myList)
输出:
String literal is: I am a single line string
Created list is: ['I', 'am', 'a', 'single', 'line', 'string']
元组也像列表一样包含数据,但是元组是不可变的,新元素不能添加到元组中,或者任何元素不能从元组中删除。我们可以如下定义一个元组。
myTuple=(1,2,"pfb",3.14)
一个 python 字典包含如下键值对形式的数据。
myDict={1:1,2:"pfb","name":'Chris', "Value":100.5}
python 中的集合可以保存无序和不重复的数据。集合中的每个元素都是唯一的。我们可以如下定义一个包含几个元素的集合。
mySet={1,2,"pfb",3.14}
结论
在这篇文章中,我们已经了解了不同类型的 python 文本,我们也看到了在 python 中如何使用列表、字典、元组和集合等集合来存储文本。
要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。你可能也会喜欢这篇关于如何在 Python 中使用 sys.argv list 的文章。
请继续关注更多内容丰富的文章。
Python 机械化备忘单
原文:https://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet
使机械化
在 web 表单中导航的一个非常有用的 python 模块是 Mechanize。在之前的一篇文章中,我写了关于“用机械化在 Python 中浏览”。今天我在 scraperwiki 上发现了这个优秀的小抄,我想和大家分享一下。
创建浏览器对象
创建一个浏览器对象,并给它一些可选的设置。
import mechanize
br = mechanize.Browser()
br.set_all_readonly(False) # allow everything to be written to
br.set_handle_robots(False) # ignore robots
br.set_handle_refresh(False) # can sometimes hang without this
br.addheaders = # [('User-agent', 'Firefox')]
打开网页
打开网页并检查其内容
response = br.open(url)
print response.read() # the text of the page
response1 = br.response() # get the response again
print response1.read() # can apply lxml.html.fromstring()
使用表单
列出页面中的表单
for form in br.forms():
print "Form name:", form.name
print form
要继续,mechanize 浏览器对象必须选择一个表单
br.select_form("form1") # works when form has a name
br.form = list(br.forms())[0] # use when form is unnamed
使用控件
循环访问窗体中的控件。
for control in br.form.controls:
print control
print "type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])
可以通过名称找到控件
control = br.form.find_control("controlname")
拥有一个选择控件可以告诉你可以选择哪些值
if control.type == "select": # means it's class ClientForm.SelectControl
for item in control.items:
print " name=%s values=%s" % (item.name, str([label.text for label in item.get_labels()]))
因为“Select”类型的控件可以有多个选择,所以它们必须用列表设置,即使它是一个元素。
print control.value
print control # selected value is starred
control.value = ["ItemName"]
print control
br[control.name] = ["ItemName"] # equivalent and more normal
文本控件可以设置为字符串
if control.type == "text": # means it's class ClientForm.TextControl
control.value = "stuff here"
br["controlname"] = "stuff here" # equivalent
控件可以设置为只读和禁用。
control.readonly = False
control.disabled = True
或者像这样禁用它们
for control in br.form.controls:
if control.type == "submit":
control.disabled = True
提交表单
完成表格后,您可以提交
response = br.submit()
print response.read()
br.back() # go back
查找链接
在 mechanize 中跟踪链接很麻烦,因为您需要有 link 对象。有时候把它们都搞定,从文本中找到你想要的链接会更容易。
for link in br.links():
print link.text, link.url
跟随链接并点击链接等同于提交并点击
request = br.click_link(link)
response = br.follow_link(link)
print response.geturl()
我希望您对 Python 中的 Mechanize 模块有了更多的了解。
URL lib 2–用户代理
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-modules-urllib2-user-agent
概观
This post will show how to add headers to a HTTP request. By default urllib2 identifies itself as Python-urllib/2.7 : GET / HTTP/1.1″ 200 151 “-” “Python-urllib/2.7” That can sometimes be confusing for certain sites. With the user_agent header in Python, it’s possible to alter that and specify any identity you like. The example below, use the Mozilla 5.10 as a User Agent, and that is also what will show up in the web server log file.
import urllib2
req = urllib2.Request('http://192.168.1.2/')
req.add_header('User-agent', 'Mozilla 5.10')
res = urllib2.urlopen(req)
html = res.read()
This is what will show up in the log file.
"GET / HTTP/1.1" 200 151 "-" "Mozilla 5.10"
Python 模块
原文:https://www.pythonforbeginners.com/modules-in-python/python-modules
这是 Python 初学者的新系列文章,应该是 Python 完全初学者的起点。把它当做备忘单、参考资料、手册或任何你想要的东西。目的是非常简短地写下 Python 的基础知识。本页将描述如何在 Python 中使用模块。
Python 模块
Python 模块使得编程更加容易。它基本上是一个由已经编写好代码组成的文件。当 Python 导入一个模块时,它首先检查模块注册表(sys.modules ),看看该模块是否已经被导入。如果是这种情况,Python 将使用现有的模块对象。导入模块有不同的方法。这也是 Python 自带电池的原因
导入模块
让我们来看看导入一个模块的不同方法
import sys
#access module, after this you can use sys.name to refer to things defined in module sys.
from sys import stdout
# access module without qualiying name.
This reads from the module "sys" import "stdout", so that we would be able to
refer "stdout"in our program.
from sys import *
# access all functions/classes in the sys module.
捕捉错误
我喜欢使用 import 语句来确保所有模块都可以加载到系统中。导入错误基本上意味着您不能使用这个模块,您应该查看回溯来找出原因。
Import sys
try:
import BeautifulSoup
except ImportError:
print 'Import not installed'
sys.exit()
Python 标准库
URL:http://docs.python.org/library/index.html系统中已经存在的模块集合,没有必要安装它们。只需导入您想要使用的模块。搜索一个模块:http://docs.python.org/py-modindex.html
Python 包索引
URL:http://pypi.python.org/pypi由社区成员创建。这是一个包含 2400 多个软件包的软件仓库
Python:更多词典
原文:https://www.pythonforbeginners.com/dictionary/python-more-dictionarys
什么是字典?
字典是具有“键”和“值”的条目的集合。
字典是可变的。您不必重新分配字典来对其进行
更改。
它们就像列表一样,除了没有指定的索引号,
而是由你自己编索引:
示例 1
testList = ["first", "second", "third"]
testDict = {0:"first", 1:"second", 2:"third"}
Python 中的字典是用{}括起来的,要创建一个字典,必须提供一个键/值。
字典中的每个键必须是唯一的。
冒号放在键和值之间(键:值)
每个键:值对由逗号分隔
示例 2
>> phonenumbers = {'Jack':'555-555', 'Jill':'555-556'}
phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"
print phonebook
{'Jill': '555-556', 'Jack': '555-555'}
字典只有一种工作方式,要从字典中获取一个值,必须输入键。
您不能提供值并获取密钥。
示例 3
phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"
print phonebook['Jill']
555-556
键/值用法
To add a key / value pair in a dictionary
>>phonebook["Matt"] = "555-557"
To change a key / value pair:
>>phonebook["Jack"] = '555-558'
To remove a key / value pair, use del
>>del phonebook["Jill"]
To see if a key exists, use has_key() method
>>phonebook.has_key("Matt")
To copy whole dictionary, use the copy() method
phonebook2 = phonebook.copy()
在存储查找结果时,我通常使用字典。
Python 运算符
原文:https://www.pythonforbeginners.com/basics/python-operators
算术运算符
Python 包括+、-、*、/、%(模数)和**(取幂)运算符
假设变量 a 保存 10,变量 b 保存 20,则:
运算符描述示例
+加法 a + b 会给出 30
–减法 b 会给出-10
*乘法 a * b 会给出 200
/除法 b / a 会给出 2
%模 b % a 会给出 0
指数 ab 会给出 10 的 20 次方
//地板除法 9//2 等于 4 且 9.0//2.0 等于 4.0
比较运算符
基本比较运算符,如==、 =,等等,用于所有
方式的值。
数字、字符串、序列和映射都可以进行比较。
下表显示了比较运算符的列表。
运算符描述
<小于
< =小于等于
==等于
大于
=大于等于
!
=不等于< >不等于
逻辑运算符
在决策结构中使用时,逻辑运算符 and 和 or 也会返回一个布尔值。
有三种逻辑运算符:and、or 和 not。
例如,只有当 x 大于 0 且小于 10 时,x > 0 且 x < 10 才成立
运算符描述
与逻辑
或逻辑
非逻辑非
Python : OS.listdir 和 endswith()
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-os-listdir-and-endswith
这个简短的脚本使用 os.listdir 函数(属于 os 模块)来搜索给定的路径(".)用于所有以“”结尾的文件。txt”。
当 for 循环找到一个匹配时,它使用 append 函数将它添加到列表“newlist”中。
查找所有以结尾的文件。文本文件(textfile)
import os
items = os.listdir(".")
newlist = []
for names in items:
if names.endswith(".txt"):
newlist.append(names)
print newlist
Python 中的 OS.walk
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk
Python 在 OS 模块中有一个很酷的内置函数,叫做 os.walk()。
OS.Walk()
OS.walk()通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。
对于以目录顶层为根的树中的每个目录(包括顶层本身),它产生一个三元组(目录路径、目录名、文件名)。
小路
root : Prints out directories only from what you specified
dirs : Prints out sub-directories from root.
files: Prints out all files from root and directories
制作剧本
有了这些信息,我们就可以创建一个简单的脚本来做到这一点。这个脚本将打印出我指定的路径(/var/log)中的所有目录、子目录和文件
import os
print "root prints out directories only from what you specified"
print "dirs prints out sub-directories from root"
print "files prints out all files from root and directories"
print "*" * 20
for root, dirs, files in os.walk("/var/log"):
print root
print dirs
print files
使用 getsize
第二个示例扩展了第一个示例,使用 getsize 函数显示了每个文件消耗了多少资源。
print "This is using getsize to see how much every file consumes"
print "---------------"
from os.path import join, getsize
for root, dirs, files in os.walk('/tmp'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
如何在 Python 中使用 Pip
原文:https://www.pythonforbeginners.com/basics/python-pip-usage
Pip 是一个软件包管理系统,用于安装和管理软件包,例如那些在 Python 包索引中找到的软件包。
皮普是什么?
Pip is a replacement for easy_install.
Packages installs the packages default under site-packages.
安装 Pip
To install Pip on your system, you can use either the source tarball or
by using easy_install.
>> $ easy_install pip
After that, the pip application is installed.
Pip 使用
How to use Pip
安装软件包
$ pip install simplejson
[... progress report ...]
Successfully installed simplejson
升级软件包
$ pip install --upgrade simplejson
[... progress report ...]
Successfully installed simplejson
移除包
$ pip uninstall simplejson
Uninstalling simplejson:
/home/me/env/lib/python2.7/site-packages/simplejson
/home/me/env/lib/python2.7/site-packages/simplejson-2.2.1-py2.7.egg-info
Proceed (y/n)? y
Successfully uninstalled simplejson
搜索包
#Search PyPI for packages
$ pip search "query"
检查包的状态
# To get info about an installed package, including its location and files:
pip show ProjectName
为什么使用 Pip 而不是 easy_install?
(The answer is taken from this [post](https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install "pip-over-easy_install") on stackoverflow)
All packages are downloaded before installation.
Partially-completed installation doesn’t occur as a result.
Care is taken to present useful output on the console.
The reasons for actions are kept track of.
For instance, if a package is being installed, pip keeps track of why that
package was required.
Error messages should be useful.
The code is relatively concise and cohesive, making it easier to use
programmatically.
Packages don’t have to be installed as egg archives, they can be installed flat.
Native support for other version control systems (Git, Mercurial and Bazaar)
Uninstallation of packages.
Simple to define fixed sets of requirements and reliably reproduce a set of
packages.
python–快速指南
原文:https://www.pythonforbeginners.com/basics/python-quick-guide
Python 基础
本文总结了最重要的 Python 主题,并提供了我们网站上更详细文章的链接和摘要信息。我们希望您将此页面加入书签,以供将来参考。
如何在电脑上设置 Python
Python 是免费和开源的,可用于 python.org 的所有操作系统。如果尚未安装,本文将帮助您安装 python。
下载并安装 Python
IPython 是一种解释型语言,这意味着当程序运行时,代码被翻译成二进制代码。
要运行 Python 代码,你需要一个 Python 解释器。Python 有不同的
版本,不是 Python 2 就是 Python 3。
Python 变量
在 Python 中,变量是文本和数字的存储占位符。
使用 Python 解释器
Python 解释器通常安装在机器
上的/usr/local/bin/python 中。
Python 评论
当使用任何编程语言时,您都需要在代码中包含注释来表示您的工作。
这详细说明了代码的某些部分的用途,并让其他开发人员知道您编写代码时在做什么。
Python 文档字符串
Python 文档字符串(或文档字符串)提供了一种将文档与 Python 模块、函数、类和方法相关联的便捷方式。
Python 中的关键词
Python 中的关键字是保留字,不能用作普通的
标识符。它们的拼写必须与书写的完全一致。
Python 中的布尔值
布尔值是两个常量对象 False 和 True。
它们用于表示真值(其他值也可以被认为是
假或真)。
操作员
Python 包括+、-、*、/、%(模数)和**(取幂)运算符。
Python 中的正则表达式
正则表达式是以紧凑语法编写的字符串模式,它允许我们快速检查给定的字符串是否匹配或包含给定的模式。
在 Python 中使用数学
Python 发行版包括 Python 解释器,一个非常简单的开发
环境,称为 IDLE、库、工具和文档。
Python 中的异常处理
在本帖中,我们将介绍 Python 如何处理异常错误。
Python 中的字符串
字符串是按顺序排列的字符列表。
任何语言都需要完成的一个常见任务是合并或组合字符串。这个过程被称为连接。
描述它的最好方式是,你把两个独立的字符串——由解释器存储——合并成一个。
Python 中的列表
Python 中最简单的数据结构,用于存储值列表。
列表是项目的集合(字符串、整数甚至其他列表)。
Python 中的字典
字典是具有“键”和“值”的条目的集合。
Python 中的字典操作
字典对象的方法
Python 中的字符串操作
字符串对象的方法
Python 中的列表操作
列表对象的方法
循环
为了让计算机做有用的工作,我们需要重复,一次又一次地循环相同的代码块。
用 Python 列出理解
列表理解提供了一种创建列表的简洁方法。
功能
函数是你可以调用的东西(可能有一些参数,你放在括号里的东西),它执行一个动作并返回值。
Python 中的条件语句
在编程中,我们经常想要检查条件并改变程序的
行为。
如果.. 否则如果..Else 语句
Conditions 测试某个东西是真还是假,它使用布尔值
(bool 类型)来检查。
模块
Python 模块使得编程更加容易。它基本上是一个由已经编写好代码组成的文件。
如何使用 PIL 的枕头、叉子
Pillow 是 PIL (Python Image Library)的一个分支,由 Alex Clark 和贡献者发起并维护。它以 PIL 法典为基础,然后演变成一个更好、更现代、更友好的 PIL 版本。它增加了对打开、操作和保存许多不同图像文件格式的支持。很多东西的工作方式和最初的 PIL 一样。
用 Python 读写文件
当您使用 Python 时,不需要为了读写文件而导入库。它是在语言中自然处理的,尽管是以一种独特的方式。
用 Python 中的语句
在 Python 中,你需要通过打开文件来访问它。您可以通过使用 open()函数来实现。Open 返回一个 file 对象,该对象包含用于获取信息和操作打开的文件的方法和属性。
Python 风格规则
这份风格指南列出了 Python 程序的注意事项。
Python 语言规则
PEP8 已经成为大多数项目的风格指南。它提倡一种可读性很强、赏心悦目的编码风格。
IPython 是 Python 编程语言的交互式 shell,它提供了增强的内省、附加的 shell 语法、制表符补全和丰富的历史记录。
python–快速入门网站
原文:https://www.pythonforbeginners.com/python-on-the-web/python-quick-start-web
Python 快速入门网站
这篇文章是我们为网络写的关于 Python 的文章的集合。什么是面向 Web 的 Python?基本上, python 程序接口/抓取网站和/或利用基于网络的 API。
如果您喜欢您阅读的内容,请使用上面的按钮
花一点时间分享它。
如何在 Python 中使用 Reddit API
在 API 文档中,您可以看到有大量的事情要做。
如何在 Python 中访问各种 Web 服务
学习 Python 的一个非常好的方法是尝试使用各种网络服务
API。为了回答这个问题,我们首先要了解一些关于 API、
JSON、数据结构等等的知识。
用 BeautifulSoup 进行网页抓取
"网络抓取(网络采集或网络数据提取)是一种从网站提取信息的计算机软件技术."
在 Python 中 HTML 解析很容易,尤其是在 BeautifulSoup 库的帮助下。在这篇文章中,我们将抓取一个网站(我们自己的)来提取所有的 URL。
使用 Python 进行推文搜索
Twitter 的 API 是基于 REST 的,将返回 XML 或 JSON 格式的结果,以及 RSS 和 ATOM 提要格式的结果。任何客户端都可以访问公共时间轴,但所有其他 Twitter 方法都需要认证。
使用 Python 的 CommandLineFu】
当您想要使用基于 Web 的服务时,常见的第一步是查看它们是否有 API。
如何在 Python 中使用 URL lib 2
urllib2 是一个 Python 模块,可用于获取 URL。
使用 Python 中的请求
Requests 是一个 Apache2 许可的 HTTP 库,用 Python 编写。它被设计成供人类用来与语言互动。
漂亮的汤 4 蟒蛇
Beautiful Soup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据。
在 Python 中使用 feed parser
在本帖中,我们将看看如何使用 Python 下载和解析整合的
提要。
用 Python 抓取网站
"网络抓取(网络采集或网络数据提取)是一种从网站提取信息的计算机软件技术."
在 Python 中 HTML 解析很容易,尤其是在 BeautifulSoup 库的帮助下。在这篇文章中,我们将抓取一个网站(我们自己的)来提取所有的 URL。
Python API 和 JSON
应用编程接口(API)是一种协议,旨在用作软件组件相互通信的接口。
Python 机械化备忘单
在 web 表单中导航的一个非常有用的 python 模块是 Mechanize。
使用 Python 中的 YouTube API
在本帖中,我们将探讨如何在 Python 中使用 YouTube API。这个程序将展示我们如何使用 API 从 YouTube 中检索提要。
如何在 Python 中使用 Vimeo API
Vimeo 提供了一个 API,让我们可以整合他们的网站,并在他们的数据上构建应用程序。
使用机械化在 Python 中浏览
Python 中的 mechanize 模块为您提供了一个类似浏览器的对象来与 web 页面进行交互。
从互联网上获取数据
urllib2 是一个用于获取 URL 的 Python 模块。
awesome 请求模块
Requests 模块是 Python 的一个优雅而简单的 HTTP 库。
解析 Python 中的 JSON
对 HTTP API 的请求通常只是带有一些查询参数的 URL。
解析 Python 中的 JSON 对象
在这篇文章中,我们将解释如何用 Python 解析 JSON 对象。
当您想从各种 web 服务访问一个 API
并以 JSON 给出响应时,知道如何解析 JSON 对象是很有用的。
什么是 JSON
JSON (JavaScript Object Notation)是一种紧凑的、基于文本的计算机数据交换格式。
Python 范围函数
原文:https://www.pythonforbeginners.com/modules-in-python/python-range-function
范围函数
Python 中内置的 range 函数对于生成列表形式的
数字序列非常有用。
给定的端点决不是生成列表的一部分;
range(10)生成 10 个值的列表,长度为 10 的
序列的合法索引。
可以让范围从另一个数字开始,或者指定一个
不同的增量(甚至是负数;
有时这被称为“步骤”):
产品系列示例
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# You can use range() wherever you would use a list.
a = range(1, 10)
for i in a:
print i
for a in range(21,-1,-2):
print a,
#output>> 21 19 17 15 13 11 9 7 5 3 1
# We can use any size of step (here 2)
>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
# The sequence will start at 0 by default.
#If we only give one number for a range this replaces the end of range value.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# If we give floats these will first be reduced to integers.
>>> range(-3.5,9.8)
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
更多阅读
Python 资源
原文:https://www.pythonforbeginners.com/basics/python-resources
Python web 应用程序框架
django 是一个高级 Python Web 框架。
http://www.djangoproject.com/
web2py
一个开源的全栈 python web 框架,用于可扩展、安全和可移植的
web 应用。http://www.web2py.com/
基于 Werkzeug 和 Jinja 2 的轻量级 Python web 框架。
http://flask.pocoo.org/
基于 Zope 工具包技术的开源 Web 框架。
http://grok.zope.org/
tornado
Tornado 是一个可扩展的、非阻塞的 web 服务器和 web 应用框架。
http://www.tornadoweb.org/
cherrypy
CherryPy 是一个面向对象的 web 应用框架。
http://cherrypy.org
一个基于 Python 的数据库 web 应用框架,集成了 Ajax。
http://www.turbogears.org
谷歌应用引擎 一个在谷歌管理的
数据中心开发和托管网络应用的平台,包括 Python。
https://developers.google.com/appengine/
一个强调灵活性和快速开发的轻量级 web 框架。
http://www . pylons project . org/projects/pylons-framework/about
**完整名单:
【http://wiki.python.org/moin/WebFrameworks **
Python 检查器/调试
pudb
PuDB 是一个全屏的、基于控制台的 Python 可视化调试器。
http://pypi.python.org/pypi/pudb
模块 pdb 为 Python 程序定义了一个交互式源代码调试器。
http://docs.python.org/2/library/pdb.html
皮林特
分析 Python 源代码,寻找 bug 和质量差的迹象。
http://www.pylint.org/
**完整名单:
【http://wiki.python.org/moin/PythonDebuggingTools **
Python shell
ipython
一个用 python 编写并为其设计的开发 shell。
http://ipython.org/
用于 Linux、BSD、OS X 和 Windows 的 python 解释器的奇特接口。
http://bpython-interpreter.org/
Python 游戏
产生了几个伟大游戏的编程挑战。
http://www.pyweek.org
Pygame 模块的所在地,也是一个链接到许多 Python 游戏的门户网站。
http://pygame.org
**完整名单:
【http://wiki.python.org/moin/PythonGames **
羧甲基淀粉钠
Skeletonz
简单、强大、可扩展、可靠。基于 Ajax 的编辑器,支持拼写检查
& UTF-8。【http://orangoo.com/skeletonz/
夹层
一个强大、一致、灵活的内容管理平台。
http://mezzanine.jupo.org
Django
Django 为内容管理提供基础支持。
https://www.djangoproject.com
Ikaro
提供内容管理功能。
http://www.hforge.org/ikaaro
Kotti
一个高级的、Pythonic 式的 web 应用框架。
http://pypi.python.org/pypi/Kotti
MediaCore Video CMS
是一个开源的媒体内容管理系统。
http://mediacore.com/
**完整名单:
【http://wiki.python.org/moin/ContentManagementSystems **
网络应用
OpenERP
一个开源的全面的商业应用套件。
https://www.openerp.com/en/
GNU Mailman
运行邮件列表的最流行的软件包之一。
http://www.gnu.org/software/mailman/
MoinMoin
一个维基引擎。
http://moinmo.in
星球
一个饲料聚合器。
http://www.planetplanet.org
Plone
一个开源的内容管理系统。
http://plone.org
一个基于网络的界面,用于浏览 CVS 和 SVN 库。
http://www.viewvc.org
跟踪
基于 Web 的 bug/问题跟踪数据库、wiki 和版本控制前端。
http://trac.edgewall.org
**完整名单:
【http://en.wikipedia.org/wiki/List_of_Python_software **
GUI 框架
Tkinter
Python 的“标准”GUI 库。
http://wiki.python.org/moin/TkInter
PyQT
用于 QT 应用开发框架的 Python 绑定。
http://wiki.python.org/moin/PyQt
WxPython
wxPython 是 Python 编程语言的 GUI 工具包。
http://www.wxpython.org/
PyGTK
一套用于 GTK+图形用户界面库的 Python 包装器。
http://pygtk.org/
**完整名单:
【http://wiki.python.org/moin/GuiProgramming **
Python 范围
在用 python 编程时,我们必须处理各种各样的结构,比如变量、函数、模块、库等等。在一些情况下,在一个地方使用的变量名也可能在不同的地方使用,而与前面的定义没有任何关系。在这篇关于 python 作用域的文章中,我们将尝试理解 python 解释器如何处理变量的定义。
Python 中的作用域是什么?
当我们在程序中定义一个变量、函数或类名时,它只能在程序的某个区域中被访问。在这个区域中,名字一旦被定义,就可以用来标识一个对象、一个变量或一个函数,这个区域称为作用域。根据变量或函数名的定义,范围可以从单个代码块(如函数)扩展到整个运行时环境。
范围的概念与名称空间密切相关,范围是作为名称空间实现的。我们可以把名称空间看作是一个将对象名称映射到对象的 python 字典。字典的键对应于名称,值对应于 python 中的对象。
在 python 中,有四种类型的作用域定义,即内置作用域、全局作用域、局部作用域和封闭作用域。我们将在接下来的章节中研究所有这些。
Python 中的内置作用域是什么?
python 中的内置作用域包含内置对象和函数定义。它是使用 python 最新版本中的内置模块实现的。
每当我们启动 python 解释器时,内置模块就会自动加载到我们的运行时环境中。因此,我们可以在程序中访问模块中定义的所有函数和对象,而无需导入它们。
像 print()、abs()、input()、int()、float()、string()、sum()、max()、sorted()等类似的函数,在使用前不需要导入,都是在内置作用域中定义的。我们可以看看内置作用域中可用的函数和对象定义,如下所示。
builtin_names = dir(__builtins__)
for name in builtin_names:
print(name)
输出:
ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
ModuleNotFoundError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
enumerate
eval
exec
exit
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
quit
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip
内置作用域是在解释器加载后创建的,随着 python 解释器的关闭而被销毁。builtins 模块中定义的所有名称都在程序的内置范围内。
什么是全局范围?
我们用来编写代码的 python 脚本被 python 解释器称为 main 模块。与 main 模块相关联的作用域称为全局作用域。
对于任何 python 程序,只能有一个全局范围。一旦程序启动,全局范围就被创建,并随着 python 程序的终止而被销毁。
我们可以从下面的程序中理解全局范围的概念。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
def print_sum():
print(temp)
return temp
在上面的程序中,myNum1 和 myNum2 在程序的全局范围内。存在于全局范围内的对象是在任何代码块之外定义的。
什么是局部范围?
python 程序中的局部作用域是为函数等代码块定义的。python 程序中的每个函数都有自己的局部作用域,在这个作用域中定义了所有的变量和对象名。
当函数被任何其他函数调用时,函数的局部范围被加载。一旦函数终止,与之相关的局部作用域也会终止。
为了理解局部范围的概念,请看下面的例子。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
def print_sum():
print(temp)
return temp
在上面的程序中,变量 num1、num2 和 temp 存在于 add()函数的局部作用域中。这些名称只在执行 add()函数之前存在。
Python 中的封闭作用域是什么?
每当一个函数被定义在任何其他函数内部时,内部函数的作用域就被定义在外部函数的作用域内部。因此,外部函数的范围被称为内部函数的封闭范围。
我们可以访问一个函数中所有的变量名,这个函数已经在它的封闭作用域中定义了。但是,我们不能访问在内部函数中定义的外部函数中的变量名。从下面的例子可以更清楚地看出这一点。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
def print_sum():
print(temp)
return temp
这里,print_sum()函数存在于 add()函数的局部作用域中。因此,在 add()函数中定义的变量名 num1、num2 和 temp 可在 print_sum()函数的作用域中访问。
结论
在本文中,我们研究了 python 中的范围概念。我们还研究了不同的作用域类型及其示例。要阅读其他 python 概念,如列表理解,敬请关注。
Python 中的日志检查器
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-script-log-checker
显示日志文件中的所有条目
This script will show all entries in the file that is specified in the log file
variable.
日志检查器脚本
In this example, I will use the /var/log/syslog file.
The for loop will go through each line of the log file and the line_split variablewill split it by lines.
If you just print the line_split, you will see an output similar to this:
>> ['Sep', '27', '15:22:15', 'Virtualbox', 'NetworkManager[710]:', '<info>', 'DNS:'..']
If you want to print each element just add the line_split[element_to_show]
#!/usr/bin/env python
logfile = open("/var/log/syslog", "r")
for line in logfile:
line_split = line.split()
print line_split
list = line_split[0], line_split[1], line_split[2], line_split[4]
print list
That's it, now you have a script that you can use for checking log files with.
监控 Apache / Nginx 日志文件
统计 Apache/Nginx 中的命中次数
This small script will count the number of hits in a Apache/Nginx log file.
它是如何工作的
This script can easily be adapted to any other log file.
The script starts with making an empty dictionary for storing the IP addresses andcount how many times they exist.
Then we open the file (in this example the Nginx access.log file) and read the
content line by line.
The for loop go through the file and splits the strings to get the IP address.
The len() function is used to ensure the length of IP address.
If the IP already exists , increase by 1.
ips = {}
fh = open("/var/log/nginx/access.log", "r").readlines()
for line in fh:
ip = line.split(" ")[0]
if 6 < len(ip) <=15:
ips[ip] = ips.get(ip, 0) + 1
print ips
测试一下
If you now browse to your website, and run the python script, you should see your IP address + the counts.
Python 安全 FTP 模块
原文:https://www.pythonforbeginners.com/modules-in-python/python-secure-ftp-module
概观
在上一篇文章中,我们介绍了 Python 中的 ftplib 模块,你可以在这里阅读
更多关于的内容。在这篇文章中,我们将介绍 pysftp 模块。
SFTP(安全文件传输协议)用于通过互联网安全地交换文件
。
这是什么?
pysftp 是一个易于使用的 sftp 模块,它利用了 paramiko 和 pycrypto。
它提供了一个简单的 sftp 接口。
一些特性是:
自动优雅地处理 RSA 和 DSS 私钥文件
支持加密的私钥文件。
现在可以启用/禁用日志记录
我为什么要用它?
当您希望通过互联网安全地交换文件时。
我如何安装它?
pysftp 列在 PyPi 上,可以使用 pip 安装。
# Search for pysftp
pip search pysftp
pysftp # - A friendly face on SFTP
#Install pysftp
pip install pysftp
我如何使用它?
使用 pysftp 很容易,我们将展示一些如何使用它的例子
列出远程目录
要连接到我们的 FTP 服务器,我们首先必须导入 pysftp 模块并
指定(如果适用)服务器、用户名和密码凭证。
运行这个程序后,您应该会看到 FTP 服务器当前目录下的所有文件和目录。
import pysftp
srv = pysftp.Connection(host="your_FTP_server", username="your_username",
password="your_password")
# Get the directory and file listing
data = srv.listdir()
# Closes the connection
srv.close()
# Prints out the directories and files, line by line
for i in data:
print i
连接参数
没有给出的参数是从环境中猜测出来的。
主持人
远程机器的主机名。
用户名
您在远程机器上的用户名。(无)
私钥
您的私钥文件。(无)
密码
您在远程机器上的密码。(无)
端口
远程机器的 SSH 端口。(22)
私人钥匙通行证
如果您的 private_key 已加密,则使用密码(无)
日志
记录连接/握手详细信息(假)
下载/上传远程文件
和前面的例子一样,我们首先导入 pysftp 模块并指定
(如果适用)服务器、用户名和密码凭证。
我们还导入了 sys 模块,因为我们希望用户指定要下载/上传的文件。
import pysftp
import sys
# Defines the name of the file for download / upload
remote_file = sys.argv[1]
srv = pysftp.Connection(host="your_FTP_server", username="your_username",
password="your_password")
# Download the file from the remote server
srv.get(remote_file)
# To upload the file, simple replace get with put.
srv.put(remote_file)
# Closes the connection
srv.close()
下一步是什么?
摆弄剧本,改变一些东西,看看会发生什么。
请尝试为其添加错误处理。如果没有传递参数会发生什么?
通过提示输入给程序增加一些交互。
来源
https://code.google.com/p/pysftp/
http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol
Python 设置
Python 是免费和开源的,可用于 python.org 的所有操作系统。如果尚未安装,本文将帮助您安装 python。
Python 已经安装在许多操作系统上。
在这篇文章中,我使用了一些来自 Google 教育资料的例子,这些资料是在这里找到的,作为帮助你设置 python 的来源之一。
我的电脑上安装 Python 了吗?
默认情况下,除 Windows 之外的大多数操作系统都已经安装了 Python
要检查 Python 是否已安装,请打开命令行(通常通过运行
“终端”程序)并键入“Python-V”
如果您看到一些版本信息,那么您已经安装了 Python。
然而,如果你得到“bash:python:command not found”,有可能
你的电脑上没有安装 Python。
请看看这篇在 diveintopython.net
发表的精彩帖子,他们描述了如何在各种操作系统上安装 Python。
Python 解释器
当您以交互模式启动 Python 时,它会提示输入下一个命令,
通常是三个大于号(>>>)。
解释器在打印第一个提示之前打印一条欢迎消息,说明其版本号和一个
版权声明,例如:
要交互式运行 Python 解释器,只需在终端中键入“Python”:
??$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 1 + 1
2
>>> you can type expressions here .. use ctrl-d to exit
我如何运行我的 Python 程序?
运行 python 程序最简单的方法是输入 "python helloworld.py"
如果在一个. py (python 扩展名)文件上设置了“执行位”,则可以通过
名称运行,而不必先键入“python”。
使用“chmod”命令设置执行位,如下所示:
$ chmod +x hello.py.
现在你可以把你的程序命名为。/hello.py
如何安装 python 窗口?
在 Windows 上做一个基本的 Python 安装很容易,只需进入python.org下载页面,选择一个版本,比如 2.7。
运行 Python 安装程序,采用所有默认值。
这将在根目录中安装 Python 并设置一些文件关联。
安装 Python 后,打开命令提示符(附件>命令提示符,或
在运行对话框中键入“cmd ”)
您应该可以通过键入“python”
然后键入“hello world . py”来运行 helloworld.py python 程序
要交互运行 python 解释器,从开始
菜单中选择运行命令,并输入 "python" ,这将在它自己的窗口中交互启动 Python。
在 Windows 上,使用 Ctrl-Z 退出(在所有其他操作系统上,使用 Ctrl-D 退出)
文本编辑器
在源文件中编写 Python 程序之前,我们需要一个编辑器来编写
源文件。
对于 Python 编程,有大量编辑器可供使用。
选择一个适合你的平台的。
你选择哪个编辑器取决于你对计算机有多少经验,
你需要它做什么,你需要在哪个平台上做。
至少,你需要一个对代码
和缩进(Notepad ++,Smultron,TextEdit,Gedit,Kate,Vi 等)有一点了解的文本编辑器..)
我如何编写 Python 程序
Python 程序只是一个可以直接编辑的文本文件。
在命令行(或终端)中,你可以运行任何你想运行的 python 程序,就像上面我们对“python hello world . py”所做的那样
在命令行提示符下,只需按向上箭头键即可调出之前键入的
命令,因此无需重新键入即可轻松运行之前的命令。
要试用您的编辑器,请编辑 helloworld.py 程序。
将代码中的【你好】改为【您好】。
保存您的编辑并运行程序以查看其新输出。
尝试添加一个“打印‘耶!’”就在现有的印刷品下面,并带有同样的
缩进。
尝试运行该程序,以查看您的编辑工作是否正常。
相关职位
如何在 Python 中使用切片
原文:https://www.pythonforbeginners.com/dictionary/python-slicing
Python 中的切片
When you want to extract part of a string, or some part of a list, you use a slice
The first character in string x would be x[0] and the nth character would be at
x[n-1].
Python also indexes the arrays backwards, using negative numbers.
The last character has index -1, the second to last character has index -2.
例子
x = "my string"
x[start:end] # items start through end-1
x[start:] # items start through the rest of the list
x[:end] # items from the beginning through end-1
x[:] # a copy of the whole list
One way to remember how slices work is to think of the indices as pointing betweencharacters, with the left edge of the first character numbered 0\.
Then the right edge of the last character of a string of n characters has index n
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0...5 in the string,
the second row gives the corresponding negative indices.
Python 中的套接字示例
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-socket-examples
Python 中的 socket 模块提供了对 BSD 套接字接口的访问。
这篇文章将展示如何使用套接字函数的例子。
要阅读更多关于 socket 模块及其功能的内容,我推荐官方文档这里。
获取 fqdn(完全限定域名)
print socket.getfqdn("8.8.8.8")
>>google-public-dns-a.google.com
将主机名转换为 IPv4 地址格式
print socket.gethostbyname("www.python.org")
>>82.94.164.162
将主机名转换为 IPv4 地址格式,扩展接口
print socket.gethostbyname_ex("www.python.org")
>>('python.org', [], ['82.94.164.162'])
返回机器的主机名..
print socket.gethostname()
>>Virtualbox123
脚本
The script below, will return the IP address of the hostname given.
If it cannot find the hostname, it will print the error to screen using
the exception handling "gaierror" (raised for address-related errors).
import socket
name = "wwaxww.python.org"
try:
host = socket.gethostbyname(name)
print host
except socket.gaierror, err:
print "cannot resolve hostname: ", name, err
If you look in the name, I misspelled the address to let you see how the error
message would look like
>>cannot resolve hostname: wwaxww.python.org [Errno -5] No address associated
with hostname
And if I run it again with the correct spelling
import socket
name = "www.python.org"
try:
host = socket.gethostbyname(name)
print host
except socket.gaierror, err:
print "cannot resolve hostname: ", name, err
>>82.94.164.162
如何在 Python 中使用排序
原文:https://www.pythonforbeginners.com/dictionary/python-sorting
整理
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order.
The original list is not changed.
The sorted() function can be customized though optional arguments.
The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True),
makes it sort backwards.
例子
Sorting Examples
**Create a list with some numbers in it** numbers = [5, 1, 4, 3, 2, 6, 7, 9]
**prints the numbers sorted** print sorted(numbers)
**the original list of numbers are not changed** print numbers
my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "EE"]
**if no argument is used, it will use the default (case sensitive)** print sorted(my_string)
**using the reverse argument, will print the list reversed** print sorted(strs, reverse=True) ## ['zz', 'aa', 'CC', 'BB']
更多阅读
Please see the [python wiki](https://wiki.python.org/moin/HowTo/Sorting/ "wki-sorting") for more things to do with sorting.
使用 urlparse 分割域
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-split-a-domain-with-urlparse
分割一个域
This is a simple script to split the domain name from a URL. It does that by usingPythons urlparse module.
import urlparse
url = "http://python.org"
domain = urlparse.urlsplit(url)[1].split(':')[0]
print "The domain name of the url is: ", domain
如何在 Python 中使用 Split
原文:https://www.pythonforbeginners.com/dictionary/python-split
了解如何在 python 中使用 split。
定义
split()方法使用用户指定的分隔符将一个字符串拆分成一个列表。如果没有定义分隔符,则使用空白(" ")。
为什么要使用 Split()函数?
在某些时候,你可能需要把一个大的字符串分解成更小的块,或者字符串。这与将字符串合并或组合成一个字符串的串联相反。
为此,您可以使用 python split 函数。它所做的是分割或分解字符串,并使用定义的分隔符将数据添加到字符串数组中。
如果在调用函数时没有定义分隔符,默认情况下将使用空格。更简单地说,分隔符是一个定义好的字符,它将放在每个变量之间。
Python Split 函数的应用示例
让我们来看一些例子。
*x* *= ‘**blue,red**,green**’*
*x.**split**(**“,”)*
*[‘blue’, ‘red’, ‘green’]*
*>>>*
*>>>* *a,b**,c* *=* *x.split**(“,”)*
*>>> a*
*‘blue’*
*>>> b*
*‘red’*
*>>> c*
*‘green’*
从这段代码中可以看出,该函数将包含三种颜色的原始字符串进行分割,然后将每个变量存储在一个单独的字符串中。这给我们留下了三串“a”、“b”和“c”。然后,当你要求解释器吐出存储在这些字符串中的变量时,你会得到适当的颜色。
很整洁,不是吗?当您大量使用字符串和变量时,它也非常有用。
让我们看另一个例子。
*>>> words = “This is random text we’re going to split apart”*
*>>> words2 =* *words.split**(“ “)*
*>>> words2*
*[‘This’, ‘is’, ‘random’, ‘text’, ‘we’re’, ‘going’, ‘to’, ‘split’, ‘apart’]*
我们在这里所做的是分割较大的字符串,并将变量作为一个列表存储在“words2”字符串下。
Python 中的基本日期和时间类型
原文:https://www.pythonforbeginners.com/basics/python-strftime-and-strptime
日期和时间
date、datetime 和 time 对象都支持 strftime(format)方法,以便在显式格式字符串的控制下创建表示时间的字符串。
以下是格式代码及其指令和含义的列表。
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.
strftime() vs strptime()
strptime()–字符串“解析”时间–用于将字符串转换为日期/时间对象。使用它将日期字符串解析为日期/时间对象。
strftime()–字符串“格式”时间–用于格式化日期对象。当您想要格式化日期时,请使用此选项。
用于字符串操作的 Python 字符串方法
原文:https://www.pythonforbeginners.com/basics/python-string-methods-for-string-manipulation
在分析文本数据时,字符串操作是最基本的技能。Python 有许多用于字符串操作的内置方法。在本文中,我们将研究用于字符串操作的最常用的 python 字符串方法。
将单词大写的 Python 字符串方法
为了在 python 中大写一个字符串的第一个字母,我们使用了 capitalize()
方法。capitalize()
方法返回一个新字符串,其中字符串的第一个字母大写。在此过程中,不会对原始字符串进行任何更改。
示例:
myString="python"
print("Original String:")
print(myString)
newString=myString.capitalize()
print("New modified string:")
print(newString)
print("original string after modification:")
print(myString)
输出:
Original String:
python
New modified string:
Python
original string after modification:
python
在输出中,我们可以看到新字符串的第一个字母已经被修改,但是调用该方法的字符串没有任何变化。
Python 字符串方法大写每个单词的第一个字符
要将每个单词的第一个字符转换成大写字母,我们可以使用 title()方法。当在字符串上调用时,它将输入字符串中每个单词的第一个字符大写,并返回一个新字符串和结果。它不会影响原始字符串。
示例:
myString="Python is a great language"
newString=myString.title()
print("Original string is:")
print(myString)
print("Output is:")
print(newString)
输出:
Original string is:
Python is a great language
Output is:
Python Is A Great Language
Python 中如何将字符串转换成小写?
casefold()
方法在 python 字符串上调用时返回一个新字符串,并将原始字符串的每个字母转换成小写。它不会改变原来的字符串。如果文本包含大写或小写字母的不规则使用,这个 python 字符串方法可用于预处理文本。
示例:
myString="PytHon"
print("Original String:")
print(myString)
newString=myString.casefold()
print("New modified string:")
print(newString)
print("original string after modification:")
print(myString)
输出:
Original String:
PytHon
New modified string:
python
original string after modification:
PytHon
另一种将字符串转换成小写的方法是lower()
方法。它还将文本字符串中的字母转换成小写,并返回一个新字符串。
示例:
myString="PytHon"
print("Original String:")
print(myString)
newString=myString.lower()
print("New modified string:")
print(newString)
print("original string after modification:")
print(myString)
输出:
Original String:
PytHon
New modified string:
python
original string after modification:
PytHon
Python 中如何把字符串转换成大写?
我们可以使用upper()
方法将一个输入字符串转换成大写。当对任何字符串调用upper()
方法时,它返回一个所有字母都大写的新字符串。它不会改变原来的字符串。
示例:
myString="PytHon"
print("Original String:")
print(myString)
newString=myString.upper()
print("New modified string:")
print(newString)
print("original string after modification:")
print(myString)
输出:
Original String:
PytHon
New modified string:
PYTHON
original string after modification:
PytHon
还有另一个名为swapcase()
的方法,它交换输入字符串中每个字母的大小写并返回一个新的字符串。它不会对调用它的输入字符串进行任何更改。
示例:
myString="PytHon"
print("Original String:")
print(myString)
newString=myString.swapcase()
print("New modified string:")
print(newString)
print("original string after modification:")
print(myString)
输出:
Original String:
PytHon
New modified string:
pYThON
original string after modification:
PytHon
python 中如何拆分字符串?
为了在 python 中拆分字符串,我们使用了split()
方法。 Python split 方法采用一个可选的分隔符,并在分隔符出现的地方分割输入字符串,并返回一个包含字符串分割部分的列表。
示例:
myString="I am A Python String"
print("Original String:")
print(myString)
newList=myString.split()
print("New List:")
print(newList)
print("when 'A' is declared as separator:")
aList=myString.split("A")
print(aList)
print("original string after modification:")
print(myString)
输出:
Original String:
I am A Python String
New List:
['I', 'am', 'A', 'Python', 'String']
when 'A' is declared as separator:
['I am ', ' Python String']
original string after modification:
I am A Python String
如果我们想把一个字符串拆分一定的次数,我们可以用rsplit()
方法代替split()
方法。rsplit()
方法采用了一个名为maxsplit
的额外参数,它是字符串被拆分的次数。输入字符串在从字符串右侧开始的maxsplit
处被分割,由rsplit()
方法返回一个包含输入字符串的maxsplit+1
片段的列表。如果没有值传递给maxsplit
参数,rsplit()
方法的工作方式与split()
方法相同。
示例:
myString="I am A Python String"
print("Original String:")
print(myString)
newList=myString.rsplit()
print("New List without maxsplit:")
print(newList)
print("when maxsplit is set at 2:")
aList=myString.rsplit(maxsplit=2)
print(aList)
print("original string after modification:")
print(myString)
输出:
Original String:
I am A Python String
New List without maxsplit:
['I', 'am', 'A', 'Python', 'String']
when maxsplit is set at 2:
['I am A', 'Python', 'String']
original string after modification:
I am A Python String
Python 中如何串联字符串?
既然我们已经看到了如何拆分字符串,那么我们可能需要在 python 中执行字符串连接。我们可以使用 "+"
操作符和join()
方法连接两个字符串。
在使用"+"
操作符时,我们只是使用"+"
操作符添加不同的字符串,并将其分配给一个新的字符串。在这里,我们可以在单个语句中使用"+"
操作符连接任意数量的字符串。
示例:
myString1="I am a "
print ("first string is:")
print(myString1)
myString2="Python String"
print("Second String is:")
print(myString2)
myString=myString1+myString2
print("Conactenated string is:")
print(myString)
输出:
myString1="I am a "
print ("first string is:")
print(myString1)
myString2="Python String"
print("Second String is:")
print(myString2)
myString=myString1+myString2
print("Conactenated string is:")
print(myString)
我们还可以使用 python 中的 join 方法连接字符串。Join 方法在一个作为分隔符的字符串上被调用,一个列表或任何其他可迭代的字符串被传递给它进行连接。它返回一个包含 iterable 中单词的新字符串,由分隔符字符串分隔。
示例:
myStringList=["I","am","a","python","string"]
print ("list of string is:")
print(myStringList)
separator=" "#space is used as separator
myString=separator.join(myStringList)
print("Concatenated string is:")
print(myString)
输出:
list of string is:
['I', 'am', 'a', 'python', 'string']
Concatenated string is:
I am a python string
Python 中如何修剪字符串?
字符串的开头或结尾可能包含额外的空格。我们可以使用 python 字符串方法删除这些空格,即strip()
、lstrip()
和rstrip()
。
方法从输入字符串的开头删除空格,并返回一个新的字符串。
从字符串末尾删除空格并返回一个新的字符串。
方法从输入字符串的开头和结尾删除空格,并返回一个新的字符串。
示例:
myString=" Python "
lstring=myString.lstrip()
rstring=myString.rstrip()
string =myString.strip()
print("Left Stripped string is:",end="")
print(lstring)
print("Right Stripped string is:",end="")
print(rstring)
print("Totally Stripped string is:",end="")
print(string)
输出:
Left Stripped string is:Python
Right Stripped string is: Python
Totally Stripped string is:Python
Python 字符串方法在换行符处拆分字符串。
通过使用 python 中的splitlines()
方法,我们可以将一个字符串转换成一列句子。该函数在换行符或换行符处拆分输入字符串,并返回一个包含输入字符串所有片段的新列表。
示例:
myString="Python is a great language.\n I love python"
slist=myString.splitlines()
print("Original string is:")
print(myString)
print("Output is:")
print(slist)
输出:
Original string is:
Python is a great language.
I love python
Output is:
['Python is a great language.', ' I love python']
结论
在本文中,我们看到了 python 字符串方法在 python 中操作字符串数据。我们已经看到了如何使用不同的方法来拆分、剥离和连接字符串。我们还看到了如何改变字符串中字母的大小写。请继续关注更多内容丰富的文章。
Python:字符串方法
原文:https://www.pythonforbeginners.com/basics/python-string-methods
字符串方法作用于调用它的字符串,如果你有一个名为 string = "Hello World "的字符串,那么字符串方法是这样调用的:string.string_method()。关于字符串方法的列表,请查看我的一篇文章,内容是关于字符串中内置方法的。
现在让我们找点乐子,展示一些例子:
string = "Hello World"
print string.isupper()
print string.upper()
print string.islower()
print string.isupper()
print string.capitalize()
print string.split()
print string.split(',')
print string.title()
print string.strip()
如果运行该程序,它应该会给出如下输出:
False
HELLO WORLD
False
False
Hello world
['Hello', 'World']
['Hello World']
Hello World
Hello World
Python 语言规则
原文:https://www.pythonforbeginners.com/cheatsheet/python-style-guide-part-1
PEP8 已经成为大多数项目的风格指南。它提倡一种可读性很强、赏心悦目的编码风格。这是 Python 社区中一个公认的约定,通常我们应该遵循这些约定。
风格指南是关于一致性的。
与本风格指南保持一致非常重要。
项目内部的一致性更重要。
一个模块或功能的一致性是最重要的。
谷歌整理了一份非常不错的风格指南摘要,可以在这里找到:http://Google-style guide . Google code . com/SVN/trunk/py guide . html
每个样式点都有一个摘要。
Python 语言规则
pychecker
- 对您的代码运行 pychecker。
进口
- 仅对包和模块使用导入。
包装
- 使用模块的完整路径名位置导入每个模块。
例外
- 例外是允许的,但必须小心使用。
全局变量
- 避免全局变量。
嵌套/局部/内部类和函数
- 嵌套/局部/内部类和函数都可以。
列出理解
- 对于简单的情况可以使用。
默认迭代器和运算符
- 对支持迭代器和操作符的类型使用默认的迭代器和操作符,比如列表、字典和文件。
发电机
- 根据需要使用发电机。
λ函数
- 好吧,一句话。
条件表达式
- 好吧,一句话。
默认参数值
- 大多数情况下没问题。
性能
- 在通常使用简单、轻量级的访问器或设置器方法的地方,使用属性来访问或设置数据。
真/假评估
- 尽可能使用“隐式”false。
不推荐使用的语言功能
- 尽可能使用字符串方法而不是字符串模块。使用函数调用语法而不是 apply。使用 list comprehensions 和 for 循环,而不是 filter 和 map,因为无论如何函数参数都是内联的 lambda。使用 for 循环代替 reduce。
词法范围
- 可以使用。
函数和方法装饰器
- 当有明显优势时,明智地使用装饰者。
穿线
- 不要依赖内置类型的原子性。
电源功能
- 避免这些功能。
Python 风格规则
原文:https://www.pythonforbeginners.com/cheatsheet/python-style-guide
正如我在 Python 风格指南第 1 部分中所写的,Google 已经整理了一份非常好的风格指南摘要。这份风格指南列出了 Python 程序的注意事项。
风格指南是关于一致性的。与本风格指南保持一致非常重要。项目内部的一致性更重要。一个模块或功能的一致性是最重要的。
PEP8 已经成为大多数项目的风格指南。它提倡一种可读性很强、赏心悦目的编码风格。PEP8 已经成为大多数项目的风格指南。它提倡一种可读性很强、赏心悦目的编码风格。这是 Python 社区中一个公认的约定,通常我们应该遵循这些约定。
页面可以在这里找到:http://Google-style guide . Google code . com/SVN/trunk/py guide . html
每个样式点都有一个摘要。
Python 风格规则
分号
不要用分号结束你的行,也不要用分号将两个命令放在同一行。
线长度
最大行长度为 80 个字符。
圆括号
少用括号。
刻痕
将代码块缩进 4 个空格。
空白行
顶层定义之间有两行空白,方法
定义之间有一行空白。
空白
遵循标点符号周围空格的标准印刷规则。
射浜线
大多数。py 文件不需要以#开头!线。
用#启动程序的主文件!/usr/bin/python。
评论
一定要为模块、函数、方法和行内注释使用正确的风格。
班级
如果一个类没有从其他基类继承,则显式从 object 继承。
这也适用于嵌套类。
用线串
对格式字符串使用%运算符,即使参数都是
字符串。
不过,用你最好的判断在+和%之间做出决定。
文件和套接字
使用完文件和套接字后,显式关闭它们。
待办事项注释
对于临时的、短期的解决方案或足够好但不完美的代码,使用 TODO 注释。
导入格式
导入应该在单独的行上。
声明
通常每行只有一条语句。
访问控制
如果一个访问函数很简单,你应该使用公共变量
而不是访问函数,以避免 Python 中函数调用的额外开销。
当添加更多功能时,您可以使用 property 来保持语法
的一致性。
命名
模块名,包名,类名,方法名,异常名,
函数名,全局常量名,全局变量名,
实例变量名,函数参数名,局部变量名。
主要的
即使是作为脚本使用的文件也应该是可导入的,一个简单的导入
不应该有执行脚本主要功能的副作用。
主要功能应该在 main()函数中。
Python 语法基础
原文:https://www.pythonforbeginners.com/basics/python-syntax-basics
在你开始写你的第一个 Python 程序之前,你必须学习一些基础知识。我们将带您了解 Python 语法的基础知识,这将有助于您的 Python 职业生涯。
在整篇文章中,我们将使用 Python 3 来涵盖这个主题。
要开始,我们先写一个非常基础的 Python 程序。
编写您的第一个 Python 程序
有两种方法可以编写和执行基本的 Python 程序:
- 在交互模式下——你写一个程序并执行它
- 使用脚本模式–在这种模式下,您可以执行并保存 Python 程序(。py 文件)
让我们看看那些在行动中。
写着“你好,世界!”论解释者
要进入交互式 Python 模式,请在终端上输入以下命令。
$ python
现在,您应该处于交互模式。
但是,如果您使用的是 IDE,您不需要键入上面的命令就可以进入交互式编程模式。
下面是执行 Hello World 程序的基本 Python 语法。
当您编写这个程序并按 enter 键时,您的 IDE 应该显示“Hello,Word!”
print("Hello World”)
您在 print(" ")的" "内书写的任何内容都会打印在您的 IDE 上。
在我们的例子中,您应该在屏幕上看到的输出是
Hello,World!
在脚本模式下运行您的第一个 Python 程序
当您在前面编写 Hello World 程序时,我们假设您将它保存在一个 Python 文件中。当您保存第一个程序时,请查找扩展名为. py 的文件。
假设您将它保存为 Hello_Python.py,下面是如何在脚本模式下执行这段代码。
首先,你保存的文件必须是可执行的。我们理想的做法是通过命令:
$ chmod +x test.py
既然您的文件是可执行的,让我们在脚本模式下运行程序。
$ python Hello_Python.py
一旦你执行这个命令,你会看到“你好,世界!”被打印在你的终端上。
"Hello, World”
在那里,你学会了你的第一个 Python 语法。
Python 关键字和标识符
在 Python 中,您应该知道总共 31 个关键字和 5 个主要标识符。
在学习 Python 技能的过程中,您会很容易习惯关键字和标识符。
Python 中的标识符是什么
Python 标识符通常是变量、函数、类、模块,也可以是任何其他对象。你在 Python 中给一个实体命名,它被称为标识符。有效的标识符以字母(a-z、A-Z 都适用)或下划线(_)开头,后面可以是零、字母、下划线或数字(0-9)。
Python 中的标识符类型:
- 变量
- 功能
- 模块
- 班级
- 其他对象
让我们检查一下 Python 中有哪些关键字
Python 语法基础–关键词
要查看所有 3 个 Python 关键字,请打开您的 IDE 并键入以下内容:
import keyword
>>> keyword.kwlist
您应该会看到类似这样的输出
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
随着新 Python 版本的发布,这些关键字可能会经常改变。记住几件事:
- 这些是固定的,不能用作标识符
- 它们区分大小写
这些关键字也经常作为保留字引用。
Python 语句
在我们继续学习 Python 语法基础知识之前,您应该知道的下一件事是行和缩进。
缩进有助于在 Python 中组织代码块。而且,它被严格执行,使您的代码在视觉上可扫描。
缩进的空间在不同的情况下会有所不同。观察下面的代码:
person = ["Dave", "Ben", "Emily"]
for x in person:
if x == "Ben":
print(x)
else:
print("not Ben")
注意“for”语句有一个空格(缩进),而“if”有两个空格。它建立了代码中发生的事情的层次结构。
试着阅读下面的代码片段,我们用文本替换了代码:
List of Persons
Go through the list of Persons:
See if Ben is there:
If yes, print Ben's name
else:
print that it's not Ben
当你在 Python 中用分号(;),你用 Python 结束一个语句。
此外,您还可以有效地使用在一行中编写多条语句。请看下面的 Python 语法示例:
person="John Doe";age=12;location="unknown"
Python 语法基础–注释
用 Python 写注释有两种不同的方式:
- 使用“#”的单行注释
- 多行注释使用""" ""
当你在三重引号内输入任何内容时,你实际上可以写多行注释,而不必在每行注释前加上“#”。一个很好的例子就是“你好,世界!”开始编程。
当您执行代码时,它不会打印您在代码中添加的注释。
Python 基本语法–命令行参数
对于 Hello_python.py 和交互式脚本,我们实际上使用了命令行参数。
这是向您介绍命令行参数的最佳方式。它们是您应该知道的 Python 语法基础的重要部分。
例如,如果你想获得更多关于一个特定程序应该如何运行的信息。
[-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-m mod : run library module as a script (terminates option list)
-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO : remove doc-strings in addition to the -O optimizations
-R : use a pseudo-random salt to make hash() values of various types be
unpredictable between separate invocations of the interpreter, as
a defense against denial-of-service attacks
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-t : issue warnings about inconsistent tab usage (-tt: issue errors)
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
see man page for details on internal buffering relating to '-u'
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
如何创建虚拟环境
虚拟环境将是你为每个新项目创建的事物之一。
您仍然可以在不创建虚拟环境的情况下处理新的 Python 项目。但是,这样做将意味着您将面临以下情况:
- 您将更改/修改依赖关系(例如,将您的默认 Python 版本从 2.7 升级到 3.x)
- 您的其他 Python 项目可能无法正常执行
要创建虚拟环境,请转到您的终端并键入以下内容:
$ virtualenv newevironment
我们刚刚创建的虚拟环境的名称 newenvironment。
要启动这个新创建的环境,请键入以下命令:
source newenvironment
Python 基本语法–安装库和包
安装 Python 库和包的最佳方式是使用 PyPI。
要安装软件包,只需键入以下命令:
pip install "package"
这里的“包”应该替换为您希望安装的库。
如果您希望安装软件包的特定版本,请更改前面的命令:
pip install "package==2.801"
但是,如果您不确定软件包版本的可用性,但希望安装一个稳定或更可靠的软件包,您可以使用以下命令:
pip install "package>=2.8"
还有其他安装 Python 包的方法,你可以去源代码发行版直接下载这些包。
接受用户输入
有两种基本的 Python 语法类型可以请求用户输入:
- 原始输入
- 投入
两者都会提示用户进行输入。
raw_input():
这个方法在 Python 3 中不再有效,新的输入是 input()。
input()
要请求用户输入,请参见下面的示例
user_input_request = input("Enter your name: ")
一旦你输入这个,你的 IDE 将要求你输入你的名字。
Python 中如何使用 sys.argv?
原文:https://www.pythonforbeginners.com/system/python-sys-argv
Python 为我们提供了不同的编程方式。在本文中,我们将讨论 python 中的 sys.argv 列表及其使用示例。
Python 中的 sys.argv 是什么?
sys argv 列表是包含 python 程序中命令行参数的列表。每当我们从命令行界面运行 python 程序时,我们可以向程序传递不同的参数。该程序将 python 文件的所有参数和文件名存储在 sys.argv 列表中。
sys argv 列表的第一个元素包含 python 文件的名称。第二个元素包含命令行参数。
您还可以找到某个程序的命令行参数的总数。为此,可以使用 len()函数找到 sys.argv 列表的长度。len()函数将列表作为其输入,并返回 sys argv 列表的长度。python 程序中的参数总数比 sys.argv 列表的长度少一个。
如果要使用命令行参数,可能需要使用 sys.argv。
要了解 sys.argv list 的更多信息,可以阅读这篇关于 python 中的命令行参数的文章。
Sys.argv 示例
要使用 sys argv,首先必须导入 sys 模块。然后,您可以使用 sys argv 列表获得 python 文件的名称和命令行参数的值。
- sys.argv 列表包含索引为 0 的 python 文件的名称。
- 它包含索引 1 处的第一个命令行参数。
- 第二个命令行参数出现在索引 2 处,依此类推。
您可以在下面的示例中观察到这一点。
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)
输出:
This is the name of the script: sysargv.py
Number of arguments in: 1
The arguments are: ['sysargv.py']
如果我用额外的参数再次运行它,我将得到以下输出:
This is the name of the script: sysargv.py
Number of arguments in: 3
The arguments are: ['sysargv.py', 'arg1', 'arg2']
结论
在本文中,我们讨论了 sys argv 列表及其在 python 中的使用。要了解更多关于 python 编程的知识,您可以阅读这篇关于在 python 中使用 with open 打开文件的文章。您可能也会喜欢这篇关于 Python 中的字符串操作的文章。
Python 系统管理
原文:https://www.pythonforbeginners.com/systems-programming/python-system-administration
概观
Python 中的 OS 模块提供了一种使用依赖于操作系统的
功能的方法。
OS 模块提供的功能允许您与运行 Python 的
底层操作系统进行交互。(Windows,Mac 或者
Linux。
您可以找到关于您所在位置或流程的重要信息。
在我们开始之前,确保您已经导入了操作系统模块" import os "
操作系统功能解释
os.system() # Executing a shell command
os.stat() # Get the status of a file
os.environ() # Get the users environment
os.chdir() # Move focus to a different directory
os.getcwd() # Returns the current working directory
os.getgid() # Return the real group id of the current process
os.getuid() # Return the current process’s user id
os.getpid() # Returns the real process ID of the current process
os.getlogin() # Return the name of the user logged
os.access() # Check read permissions
os.chmod() # Change the mode of path to the numeric mode
os.chown() # Change the owner and group id
os.umask(mask) # Set the current numeric umask
os.getsize() # Get the size of a file
os.environ() # Get the users environment
os.uname() # Return information about the current operating system
os.chroot(path) # Change the root directory of the current process to path
os.listdir(path)# List of the entries in the directory given by path
os.getloadavg() # Show queue averaged over the last 1, 5, and 15 minutes
os.path.exists()# Check if a path exists
os.walk() # Print out all directories, sub-directories and files
os.mkdir(path) # Create a directory named path with numeric mode mode
os.remove(path) # Remove (delete) the file path
os.rmdir(path) # Remove (delete) the directory path
os.makedirs(path)# Recursive directory creation function
os.removedirs(path) # Remove directories recursively
os.rename(src, dst) # Rename the file or directory src to dst
操作系统功能示例
让我们开始看看如何使用这些操作系统功能。
#Get current working directory with os.getcwd()
print os.getcwd()
#Get the status of a file with os.stat()
print "Getting the status of: ", os.stat('/usr/bin/python')
#Execute a shell command with os.system()
os.system('ls -l')
#Return the current process id with os.getpid()
print os.getpid()
os.chmod(path, mode)
#Change the owner and group id of path to the numeric uid and gid with os.chown()
os.chown(path, uid, gid)
#Processes in the system run queue averaged over the last 1, 5, and 15 minutes
print os.getloadavg()
#Check if a path exists with os.path.exists()
if os.path.exists("file.txt"):
#Create a new directory named 'new_directory' if it doesn't exist already"
os.path.exists("new_directory") or os.mkdir("new_directory")
#Check if the path is a directory or a file with os.path.isdir() & os.path.isfile()
path = "/tmp"
if os.path.isdir(path): print "That's a directory"
if os.path.isfile(path): print "That's a file"
#Create a directory with os.makedir()
print os.mkdir('new_directory', 0666)
#Recursive create directories with os.makedirs()
os.makedirs('dir_a/dir_b/dir_c')
#Remove a directory with os.rmdir()
print os.rmdir('directory')
#Recursively remove empty directories with os.rmdirs()
os.removedirs('dir_a/dir_b/dir_c')
#Rename a file with os.rename()
print os.rename('/path/to/old/file', '/path/to/new/file')
#Rename a file with shutil.move()
print shutil.move('/path/to/old/file', '/path/to/new/file')
#Rename a file with shutil.copy()
print shutil.copy('/path/to/old/file', '/path/to/new/file')
#Get the users home directory
print os.path.expanduser('~')
#Check read permissions with os.access()
path = '/tmp/file.txt'
print os.access(path, os.R_OK)
#Get the users environment with os.environmen()
home = os.environ['HOME']
print home
#Move focus to a different directory with os.chdir()
print os.chdir('/tmp')
#Print out all directories, sub-directories and files with os.walk()
for root, dirs, files in os.walk("/tmp"):
print root
print dirs
print files
#Get the last time a directory was accessed with os.path.getatime()
os.path.getatime('/tmp')
#Get the last time a directory was modified with os.path.getmtime()
os.path.getmtime('/tmp')
#Get the user ID with os.getuid()
if os.getuid() != 0: print "you are not root"
#Get the group ID with os.getgid()
print os.getgid()
#Return the name of the user logged in with os.getlogin()
print os.getlogin()
#Returns a list of all files in a directory with os.listdir()
for filename in os.listdir("/tmp"):
print "This is inside /tmp", filename
#Get the size of a file with os.path.getsize()
path.getsize("/tmp/file.txt")
当您觉得您的 shell 脚本非常有限时,在日常工作中使用 Python 是自动化系统管理任务的好方法。
如何用 Shutil 复制和移动文件?
原文:https://www.pythonforbeginners.com/os/python-the-shutil-module
什么是 Shutil?
shutil 模块帮助你自动复制文件和目录。
这样就省去了没有实际处理时打开、读取、写入和关闭文件的步骤。
这是一个实用模块,可以用来完成任务,如:复制,移动,或删除目录树
shutil. copy ( src , dest )
# Basically the unix command cp src dst.
# this copies the source file to the destination directory
# the destination directory has to exist
# if the filename already exists there, it will be overwritten
# access time and last modification time will be updated
# the same filename is used
# the permissions of the file are copied along with the contents.
import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
if files.endswith(".txt"):
shutil.copy(files,destination)
###########
shutil.copyfile ( src , dest )
# copy data from src to dest
# both names must be files.
# copy files by name
import shutil
shutil.copyfile('/path/to/file', '/path/to/other/phile')
############
shutil.move
# recursively move a file or directory (src) to another location (dst).
# if the destination is a directory or a symlink to a directory, then src is moved
inside that directory.
# the destination directory must not already exist.
# this would move files ending with .txt to the destination path
import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
if files.endswith(".txt"):
shutil.move(files,destination)
####################
shutil.copytree ( src , dest )
# recursively copy the entire directory tree rooted at src to dest.
# dest must not already exist.
# errors are reported to standard output.
####################
import shutil
import os
SOURCE = "samples"
BACKUP = "samples-bak"
# create a backup directory
shutil.copytree(SOURCE, BACKUP)
print os.listdir(BACKUP)
####################
shutil.rmtree ( path )
# recursively delete a directory tree.
# This removes the directory 'three' and anything beneath it in the filesystem.
import shutil
shutil.rmtree('one/two/three')
在 Python 中尝试 and Except
原文:https://www.pythonforbeginners.com/error-handling/python-try-and-except
之前我写过 Python 中的错误和异常。这篇文章将讲述如何处理这些问题。异常处理允许我们在出现异常时继续(或终止)程序。
错误处理
Python 中的错误处理是通过使用异常来完成的,这些异常在 try 块中被捕获,在 except 块中被处理。
试着除了
如果遇到错误,try 块代码将停止执行,并向下转移到 except 块。
除了在 try 块之后使用 except 块之外,还可以使用 finally 块。
无论是否发生异常,finally 块中的代码都将被执行。
引发异常
您可以使用 raise exception [,value]语句在自己的程序中引发异常。
引发异常会中断当前的代码执行,并返回异常,直到它被处理。
例子
一个 try 块如下所示
try:
print "Hello World"
except:
print "This is an error message!"
异常错误
一些常见的异常错误有:
io error-如果文件无法打开。
ImportError–如果 python 找不到模块
value error–当内置操作或函数收到类型正确但值不合适的参数时引发
keyboard interrupt—当用户点击中断键(通常是 Control-C 或 Delete)时引发
e ofError–当一个内置函数(input()或 raw_input())在没有读取任何数据的情况下遇到文件结束条件(EOF)时引发
例子
让我们看一些使用异常的例子。
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occured.')
Python 中有许多内置的异常。
Python:元组概述
原文:https://www.pythonforbeginners.com/basics/python-tuples-overview
Tuple is another data type in Python.
A tuple consists of values separated by commas.
Tuples are always enclosed in parentheses.
Tuples are for immutable.
Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
Empty tuples are constructed by an empty pair of parentheses.
Tuple with one item is constructed by following a value with a comma.
元组示例
x = () # empty tuple
x = (0,) # one item tuple
x = (0, 1, 2, "abc") # four item tuple: indexed x[0]..x[3]
x = 0, 1, 2, "abc" # parenthesis are optional
x = (0, 1, 2, 3, (1, 2)) # nested subtuples
y = x[0] # indexed item
y = x[4][0] # indexed subtuple
x = (0, 1) * 2 # repeat
x = (0, 1, 2) + (3, 4) # concatenation
for item in x: print item # iterate through tuple
b = 3 in x # test tuple membership
在 Python 中使用 Telnet
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-using-telnet
在 Python 中使用 Telnet
To make use of Telnet in Python, we can use the telnetlib module.
That module provides a Telnet class that implements the Telnet protocol.
The Telnet module have several methods, in this example I will make use of these:
read_until, read_all() and write()
Python 中的 Telnet 脚本
Let's make a telnet script
import getpass
import sys
import telnetlib
HOST = "hostname"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "
")
if password:
tn.read_until("Password: ")
tn.write(password + "
")
tn.write("ls
")
tn.write("exit
")
print tn.read_all()
At ActiveState you can find more Python scripts using the telnetlib,
for example [this](https://code.activestate.com/recipes/52228/ "code") script.
For more information about using the Telnet client in Python, please see the
[official documentation](https://docs.python.org/2/library/telnetlib.html "python").
Python 中的变量
原文:https://www.pythonforbeginners.com/basics/python-variables
变量
您可以使用任何字母、特殊字符“_”和提供的每个数字
而不是以它开头。
在 Python 中有特殊含义的空格和符号,如“+”和“-”是不允许的
。
我通常使用小写字母,单词之间用下划线隔开,以提高可读性。
记住变量名是区分大小写的。
Python 是动态类型的,这意味着你不必声明每个变量是什么类型。
在 Python 中,变量是文本和数字的存储占位符。
它必须有一个名称,以便您能够再次找到它。
变量总是被赋予等号,后跟
变量的值。
Python 有一些保留字,不能用作变量名。
这些变量在程序中被引用来得到它的值。
变量的值可以在以后更改。
将值 10 存储在名为 foo 的变量中
foo = 10
将 foo+10 的值存储在名为 bar 的变量中
bar = foo + 10
一些不同变量类型的列表
x = 123 # integer
x = 123L # long integer
x = 3.14 # double float
x = "hello" # string
x = [0,1,2] # list
x = (0,1,2) # tuple
x = open(‘hello.py’, ‘r’) # file
You can also assign a single value to several variables simultaneously multiple
assignments.
Variable a,b and c are assigned to the same memory location,with the value of 1
a = b = c = 1
例子
length = 1.10
width = 2.20
area = length * width
print "The area is: " , area
This will print out: The area is: 2.42
更多阅读
如何在 Python 中使用 Virtualenv
原文:https://www.pythonforbeginners.com/basics/python-virtualenv-usage
这篇文章将描述什么是 Virtualenv,以及你如何使用它。
什么是 Virtualenv?
Virtualenv is a tool to create isolated Python environments, it's perhaps the
easiest way to configure a custom Python environment.
Virtualenv allows you to add and modify Python modules without access to the
global installation.
它是做什么的?
The basic problem being addressed is one of dependencies and versions, and
indirectly permissions.
Imagine you have an application that needs version 1 of LibFoo, but another
application requires version 2\.
How can you use both these applications?
If you install everything into /usr/lib/python2.7/site-packages (or whatever your
platform’s standard location is), it’s easy to end up in a situation where you
unintentionally upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be?
If an application works, any change in its libraries or the versions of those
libraries can break the application.
Also, what if you can’t install packages into the global site-packages directory?
For instance, on a shared host.
In all these cases, virtualenv can help you.
It creates an environment that has its own installation directories, that doesn’t
share libraries with other virtualenv environments
如何安装 Virtualenv?
There are a few ways to install virtualenv on your machine.
You can use either the source tarball, pip or by using easy_install.
简单安装
$ sudo easy_install virtualenv
Searching for virtualenv
Reading http://pypi.python.org/simple/virtualenv/
Reading http://www.virtualenv.org
Reading http://virtualenv.openplans.org
Best match: virtualenv 1.8.2
Downloading http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.8.2.tar.gz...
processing virtualenv-1.8.2.tar.gz
.....
....
Processing dependencies for virtualenv
Finished processing dependencies for virtualenv
源球安装
Get the latest version from here: http://pypi.python.org/packages/source/v/virtualenv/
wget http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.8.tar.gz
tar xzvf virtualenv-1.8.tar.gz
python virtualenv-1.8/virtualenv.py $HOME/env
Pip 安装
pip install virtualenv
使用
To create virtual environments, you can use the virtualenv command.
Create an environment called "foobar":
virtualenv foobar
Activate the environment by sourcing its activate script, which is located in the
environment's bin/ directory:
source foobar/bin/activate
This will change your $PATH so its first entry is the virtualenv’s bin/ directory.
If you install a package in your virtual environment, you'll see that executable
scripts are placed in foobar/bin/ and eggs in foobar/lib/python2.X/site-packages/
easy_install yolk
Yolk is a small command line tool which can, among other things, list the
currently installed Python packages on your system:
yolk -l
Virtualenv inherits packages from the system's default site-packages directory.
This is especially useful when relying on certain packages being available,
so you don't have to go through installing them in every environment.
To leave an environment, simply run deactivate:
deactivate
If you execute he yolk command now, you will see that it won't work because the
package was installed only in your virtual environment.
Once you reactivate your environment it will be available again.
来源
I used different sources to find information for this article:
the official virtualenv [website](http://www.virtualenv.org/en/latest/index.html "virtualenv latest"), from Chris Scott "[A Primer on virtualenv](http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ "a primer on virtualenv")" and
from Arthur Koziel '[Working with virtualenv](http://www.arthurkoziel.com/2008/10/22/working-virtualenv/ "working-virtualenv")'
在 Python 中使用 web 浏览器
原文:https://www.pythonforbeginners.com/code-snippets-source-code/python-webbrowser
Python 中的 webbrowser 模块提供了一个界面来显示基于 Web 的文档。
网络浏览器
在大多数情况下,只需从这个模块调用 open()函数就可以了。
在 Unix 中,图形浏览器是 X11 下的首选,但是如果图形浏览器不可用或者 X11 显示不可用,将使用文本模式浏览器。
如果使用文本模式浏览器,调用进程将一直阻塞,直到用户退出浏览器。
用法示例
webbrowser.open_new(url)
Open url in a new window of the default browser, if possible, otherwise,
open url in the only browser window.
webbrowser.open_new_tab(url)
Open url in a new page (“tab”) of the default browser, if possible,
otherwise equivalent to open_new().
Webbrowser 脚本
这个例子将要求用户输入一个搜索词。一个新的浏览器标签将会打开,并在谷歌的搜索栏中输入搜索词。
import webbrowser
google = raw_input('Google search:')
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % google)
脚本 webbrowser 可以用作模块的命令行界面。它接受一个 URL 作为参数。
它接受以下可选参数:
- -n 在新的浏览器窗口中打开 URL
- -t 在新的浏览器页面(“选项卡”)中打开 URL
Python 网站和教程
原文:https://www.pythonforbeginners.com/basics/python-websites-tutorials
下面的列表是为了帮助新的 python 程序员在网上找到最好的 Python 网站和教程!
Python 网站教程
Python 来了
Python 交互式教程
Python 书籍
学习 Python
面向儿童的 Python:有趣的编程入门
Python 食谱
使用 Python 的计算和编程简介
Python 视频/截屏
Python 讨论/论坛
Python 源代码
Python 游戏教程
Python 抓取教程
Python 系统管理教程
Python 练习
Python Web 框架
Flask:Python 的微框架
Django:最大的基于 Python 的 web 框架
Bottle:一个快速、简单、轻量级的用于 Python 的 WSGI 微型 web 框架
Pyramid:一个非常通用的开源 Python web 框架
CherryPy:一个极简的 Python Web 框架
更多阅读
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
在 Python 中使用 While 循环
原文:https://www.pythonforbeginners.com/loops/python-while-loop
概观
在这篇文章中,我将讲述 Python 中的 While 循环。
如果你读过早先的帖子 For 和 While 循环,你可能会认识到很多这种情况。
从 0 数到 9
这个小脚本会从 0 数到 9。
i = 0
while i < 10:
print i
i = i + 1
它是做什么的?
在 while 和冒号之间,有一个值首先为真,但随后为假。
只要该语句为真,其余的代码就会运行。
将要运行的代码必须在缩进的块中。
i = i + 1 每运行一次,I 值就加 1。
注意不要形成一个永恒的循环,也就是循环一直持续到你按下 Ctrl+C。
while True:
print "Hello World"
这个循环意味着 while 循环将永远为真,并将永远打印 Hello World。
Python 的内置异常
原文:https://www.pythonforbeginners.com/error-handling/pythons-built-in-exceptions
Python 的内置异常
基本异常
所有内置异常的基类。
例外
所有内置的、非系统退出的异常都是从这个类派生的。
所有用户定义的异常也应该从此类派生。
标准误差
除 StopIteration、GeneratorExit、
KeyboardInterrupt 和 SystemExit 之外的所有内置异常的基类。StandardError 本身是从 Exception 派生的。
算术误差
针对各种
算术错误引发的内置异常的基类:OverflowError、ZeroDivisionError、FloatingPointError
LookupError
当
映射或序列上使用的键或索引无效时引发的异常的基类:IndexError,KeyError。
这可以由 sys.setdefaultencoding()直接引发
环境错误
Python 系统之外可能发生的异常的基类:
IOError,OSError。
断言错误
assert 语句失败时引发。
属性错误
当属性引用或赋值失败时引发。
埃费罗尔
当其中一个内置函数(input()或 raw_input())在没有读取任何数据的情况下遇到
文件结束条件(e of)时引发。
浮点错误
浮点运算失败时引发。
发电机出口
调用生成器的 close()方法时引发。
它直接继承自 Exception 而不是 StandardError,因为从技术上来说它不是一个错误。
io 错误
当 I/O 操作(如打印语句、内置 open()
函数或 file 对象的方法)由于 I/O 相关的原因而失败时引发,
例如,“找不到文件”或“磁盘已满”。
此类派生自 EnvironmentError。
导入错误
当 import 语句找不到模块定义或当
from…import 找不到要导入的名称时引发。
索引错误
当序列下标超出范围时引发。
KeyError
在现有键集中找不到映射(字典)键时引发。
键盘中断
当用户按下中断键(通常是 Control-C 或 Delete)时引发。
存储器错误
当一个操作耗尽了内存,但这种情况仍可能被
挽救(通过删除一些对象)时引发。
NameError
找不到本地或全局名称时引发。
这只适用于非限定名。
相关值是一个错误消息,其中包含可能找不到的名称
。
notimplemontederror
该异常源自 RuntimeError。
在用户定义的基类中,当抽象方法需要派生类来重写方法时,它们应该抛出这个异常。
OSError
该类派生自 EnvironmentError,主要用作
os 模块的 os.error 异常。
溢出误差
当算术运算的结果太大而无法表示时引发。
参考错误
当由
weakref.proxy()函数创建的弱引用代理在被垃圾收集后用于访问 referent
的属性时,会引发该异常。
RuntimeError
当检测到不属于任何其他类别的错误时引发。
停止迭代:
由迭代器的 next()方法引发,表示没有其他值。
句法误差
当分析器遇到语法错误时引发。
系统误差
当解释器发现一个内部错误时引发,但是情况看起来没有严重到使它放弃所有希望。
相关的值是一个字符串,指示出了什么问题(在低级术语中)。
系统退出
此异常由 sys.exit()函数引发。
不处理时,Python 解释器退出;不打印堆栈回溯。
如果关联值是一个普通整数,则指定系统退出状态
(传递给 C 的 exit()函数);如果没有,则退出状态为零;
如果它有另一种类型(比如字符串),对象的值被打印出来,
退出状态为 1。
TypeError
当操作或函数应用于不适当的
类型的对象时引发。
关联的值是一个字符串,给出关于类型不匹配的详细信息。
unboundlocalrerror
当引用函数或方法中的局部变量,但没有值绑定到该变量时引发。
UnicodeDecodeError
当发生与 Unicode 相关的编码或解码错误时引发。
它是 ValueError 的子类。
unicode encoded error
当编码过程中出现与 Unicode 相关的错误时引发。
它是 UnicodeError 的子类。
UnicodeError
当解码过程中出现与 Unicode 相关的错误时引发。
它是 UnicodeError 的子类。
UnicodeTranslateError
当翻译过程中出现与 Unicode 相关的错误时引发。
它是 UnicodeError 的子类。
ValueError
当内置操作或函数接收到一个类型为
但值不合适的参数,并且这种情况不是由
更精确的异常(如 IndexError)描述时引发。
WindowsError
当发生特定于 Windows 的错误或错误号与错误值不对应时引发。
零除法错误
当除法或模运算的第二个参数为零时引发。
相关值是一个字符串,指示操作数和
操作的类型。
Python 的操作系统模块
概观
Python 中的 OS 模块提供了一种使用操作系统相关功能的方式。
OS 模块提供的功能允许您与运行 Python 的底层操作系统进行交互——无论是 Windows、Mac 还是 Linux。
您可以找到关于您所在位置或流程的重要信息。在这篇文章中,我将展示其中的一些功能。
操作系统功能
**import os**
Executing a shell command
**os.system()**
Get the users environment
**os.environ()**
#Returns the current working directory.
**os.getcwd()**
Return the real group id of the current process.
**os.getgid()**
Return the current process’s user id.
**os.getuid()**
Returns the real process ID of the current process.
**os.getpid()**
Set the current numeric umask and return the previous umask.
**os.umask(mask)**
Return information identifying the current operating system.
**os.uname()**
Change the root directory of the current process to path.
**os.chroot(path)**
Return a list of the entries in the directory given by path.
**os.listdir(path)**
Create a directory named path with numeric mode mode.
**os.mkdir(path)**
Recursive directory creation function.
**os.makedirs(path)**
Remove (delete) the file path.
**os.remove(path)**
Remove directories recursively.
**os.removedirs(path)**
Rename the file or directory src to dst.
**os.rename(src, dst)**
Remove (delete) the directory path.
**os.rmdir(path)**
Python 中的队列
你一定在现实生活中见过排队等候预约医生或在餐馆点餐的情形。队列数据结构遵循后进先出(LIFO)顺序来访问元素。首先添加的元素只能被访问或删除。在本文中,我们将研究队列数据结构背后的基本概念,并用 python 实现它。
如何用 python 实现队列?
队列是一种线性数据结构,在这种结构中,我们只能访问或删除最先添加到队列中的元素。我们将使用一个列表实现一个队列。为了实现,我们将定义一个队列类,它将有一个包含元素的列表和一个包含列表长度的 queueLength 字段。python 中的队列类实现如下。
class Queue:
def __init__(self):
self.queueList=list()
self.queueLength=0
在 python 中向队列添加元素
当我们向队列中添加一个元素时,这个操作被称为入队操作。要实现入队操作,我们只需将元素添加到队列的列表中。然后,我们将队列长度增加 1。实现入队操作的 enQueue()方法将元素作为参数并执行操作。这可以如下实现。
def enQueue(self,data):
self.queueList.append(data)
self.queueLength=self.queueLength+1
在 python 中从队列中移除元素
当我们从队列中删除一个元素时,这个操作称为出列操作。为了实现出列操作,我们将只弹出队列中列表的第一个元素。然后,我们将队列长度减 1。在出队操作之前,我们将检查队列是否为空。如果是,将使用 python try except 引发一个异常,并显示队列为空的消息。否则将执行出列操作。实现出列操作的 deQueue()方法可以按如下方式实现。
def deQueue(self):
try:
if self.queueLength==0:
raise Exception("Queue is Empty")
else:
temp=self.queueList.pop(0)
self.queueLength=self.queueLength-1
return temp
except Exception as e:
print(str(e))
找出队列的长度
要找到队列的长度,我们只需查看 queueLength 变量的值。length()方法实现如下。
def length(self):
return self.queueLength
检查队列是否为空
要检查队列是否为空,我们必须确定 queueLength 是否为 0。isEmpty()方法将实现如下逻辑。
def isEmpty(self):
if self.queueLength==0:
return True
else:
return False
获取队列中的前一个元素
要获得队列中的前一个元素,我们必须返回队列中列表的第一个元素。这可以如下实现。
def front(self):
try:
if self.queueLength==0:
raise Exception("Queue is Empty")
else:
temp=self.queueList[-1]
return temp
except Exception as e:
print(str(e))
下面是用 python 实现队列的完整代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 20:15:56 2021
@author: aditya1117
"""
class Queue:
def __init__(self):
self.queueList=list()
self.queueLength=0
def enQueue(self,data):
self.queueList.append(data)
self.queueLength=self.queueLength+1
def deQueue(self):
try:
if self.queueLength==0:
raise Exception("Queue is Empty")
else:
temp=self.queueList.pop(0)
self.queueLength=self.queueLength-1
return temp
except Exception as e:
print(str(e))
def isEmpty(self):
if self.queueLength==0:
return True
else:
return False
def length(self):
return self.queueLength
def front(self):
try:
if self.queueLength==0:
raise Exception("Queue is Empty")
else:
temp=self.queueList[-1]
return temp
except Exception as e:
print(str(e))
结论
在本文中,我们已经理解了队列背后的概念,并用 python 实现了它。复制上面给出的完整代码,将其粘贴到您的 IDE 中,尝试操作以理解概念,并查看队列与其他数据结构(如 python 字典、列表和集合)有何不同。请继续关注更多内容丰富的文章。
Python 中某个范围内的随机数
原文:https://www.pythonforbeginners.com/basics/random-number-in-a-range-in-python
Python 为我们提供了随机模块来在我们的程序中生成随机数。在本文中,我们将讨论在 python 中创建给定范围内的随机数的不同方法。
使用 randint()函数在一个范围内产生随机数
要在一个范围内创建一个随机数,我们可以使用 randint()
函数。randint()
函数将范围的下限和上限分别作为第一个和第二个输入参数。执行后,它返回一个介于下限和上限之间的随机数。这里,下限和上限是包括在内的,并且新生成的随机数可以等于上限或下限。您可以使用randint()
功能创建一个范围内的随机数,如下所示。
import random
upper_limit = 1000
lower_limit = 0
print("The lower limit of the range is:", lower_limit)
print("The upper limit of the range is:", upper_limit)
number = random.randint(lower_limit, upper_limit)
print("The random number is:", number)
输出:
The lower limit of the range is: 0
The upper limit of the range is: 1000
The random number is: 739
使用 choice()函数在一个范围内的随机数
不使用randint()
函数,我们可以使用 random 模块中定义的choice()
函数来创建一个随机数。为此,我们将首先使用range()
函数创建一个数字序列。range()
函数将序列的下限作为第一个参数,将序列的上限作为第二个参数,将序列中两个连续数字的差作为第三个可选参数。执行后,它返回一个包含数字序列的列表。
创建列表后,我们将把它作为输入参数传递给choice()
函数。choice 函数将列表作为其输入参数,并从列表中返回一个随机数。这样,我们可以在给定的范围内创建一个随机数,如下所示。
import random
upper_limit = 1000
lower_limit = 0
print("The lower limit of the range is:", lower_limit)
print("The upper limit of the range is:", upper_limit)
range_of_nums = range(lower_limit, upper_limit)
number = random.choice(range_of_nums)
print("The random number is:", number)
输出:
The lower limit of the range is: 0
The upper limit of the range is: 1000
The random number is: 848
要一次获得多个随机数,可以使用choices()
功能。choices()
功能与choice()
功能完全相同。此外,它将所需随机数的计数作为第二个输入参数,并返回指定随机数的列表,如下所示。
import random
upper_limit = 1000
lower_limit = 0
print("The lower limit of the range is:", lower_limit)
print("The upper limit of the range is:", upper_limit)
range_of_nums = range(lower_limit, upper_limit)
numbers = random.choices(range_of_nums, k=3)
print("The three random numbers are:", numbers)
输出:
The lower limit of the range is: 0
The upper limit of the range is: 1000
The three random numbers are: [105, 858, 971]
使用 Numpy 模块
我们还可以使用 numpy 模块中定义的函数生成一个范围内的随机数。例如,您可以使用numpy.random.randint()
函数代替random.randint()
函数来生成一个随机数,如下所示。
import numpy
upper_limit = 1000
lower_limit = 0
print("The lower limit of the range is:", lower_limit)
print("The upper limit of the range is:", upper_limit)
number = numpy.random.randint(lower_limit, upper_limit)
print("The random number is:", number)
输出:
The lower limit of the range is: 0
The upper limit of the range is: 1000
The random number is: 144
类似地,您可以使用 numpy.random.choice()
函数在如下范围内生成随机数。
import numpy
upper_limit = 1000
lower_limit = 0
print("The lower limit of the range is:", lower_limit)
print("The upper limit of the range is:", upper_limit)
range_of_nums = range(lower_limit, upper_limit)
number = numpy.random.choice(range_of_nums)
print("The random number is:", number)
输出:
The lower limit of the range is: 0
The upper limit of the range is: 1000
The random number is: 264
脑震荡
在本文中,我们讨论了用 python 在一个范围内生成随机数的不同方法。我们还讨论了如何创建数字列表。要了解更多关于 python 中的列表,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
将 CSV 读入 Python 中的列表列表
原文:https://www.pythonforbeginners.com/basics/read-csv-into-a-list-of-lists-in-python
我们经常需要处理 csv 文件来分析与业务问题相关的数据。在本文中,我们将讨论如何将 csv 文件读入 python 中的列表。
使用 CSV.reader()将 CSV 读入列表列表中
Python 为我们提供了 csv 模块来处理 python 中的 csv 文件。为了从一个csv
文件中访问数据,我们经常使用一个借助于csv.reader()
方法创建的 reader 对象。
创建 reader 对象后,我们可以将 csv 文件读入一个列表列表中。为此,我们将首先在读取模式下使用open()
功能打开 csv 文件。open()
函数将 csv 文件的文件名作为其第一个输入参数,将文字“r
”作为其第二个输入参数,以表示该文件将以只读模式打开。执行后,open()
方法返回一个引用 csv 文件的 file 对象。
现在,我们将 file 对象传递给reader()
方法来创建一个 reader 对象。reader 对象实际上是一个迭代器,它将 csv 文件中的每一行都包含为一个列表。我们可以使用 for 循环访问 csv 文件的每一行,并将它读入如下的列表列表中。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.reader(myFile)
myList = []
for record in reader:
myList.append(record)
print("The list of lists is:")
print(myList)
输出:
The list of lists is:
[['Roll', 'Name', 'Language'], ['1', 'Aditya', 'Python'], ['2', 'Sam', ' Java'], ['3', ' Chris', ' C++']]
如果您想跳过 csv 文件的文件头,您可以使用 next()
功能。当在迭代器上执行时,next()
函数从迭代器返回一个元素,并将迭代器移动到下一个元素。在 for 循环之外,可以使用一次next()
函数将 csv 文件读入一个没有头文件的列表,如下所示。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.reader(myFile)
print("The header is:")
print(next(reader))
myList = []
for record in reader:
myList.append(record)
print("The list of lists is:")
print(myList)
输出:
The header is:
['Roll', 'Name', 'Language']
The list of lists is:
[['1', 'Aditya', 'Python'], ['2', 'Sam', ' Java'], ['3', ' Chris', ' C++']]
您可以使用list()
构造函数,而不是使用 for 循环从 reader 对象读取 csv。这里,我们将把 reader 对象传递给list()
构造函数,它将返回如下所示的列表列表。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.reader(myFile)
myList = list(reader)
print("The list of lists is:")
print(myList)
输出:
The list of lists is:
[['Roll', 'Name', 'Language'], ['1', 'Aditya', 'Python'], ['2', 'Sam', ' Java'], ['3', ' Chris', ' C++']]
类似地,您可以使用list()
构造函数以及next()
方法和csv.reader()
方法来读取一个没有头文件的 csv 文件,如下所示。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.reader(myFile)
print("The header is:")
print(next(reader))
myList = list(reader)
print("The list of lists is:")
print(myList)
输出:
The header is:
['Roll', 'Name', 'Language']
The list of lists is:
[['1', 'Aditya', 'Python'], ['2', 'Sam', ' Java'], ['3', ' Chris', ' C++']]
结论
在本文中,我们讨论了用 python 将 csv 文件读入列表列表的不同方法。要了解更多关于列表的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
我希望你喜欢阅读这篇文章。
快乐学习!
用 Python 将 CSV 读入字典列表
原文:https://www.pythonforbeginners.com/basics/read-csv-into-list-of-dictionaries-in-python
csv 文件用于存储结构化数据,CSV 文件中的每一行都存储一个条目,其中每个值都与列名相关联。类似地, python 字典用于存储 python 中的键值对。在本文中,我们将讨论如何将 csv 文件读入 python 中的字典列表。
使用 csv 将 CSV 读入字典列表。字典阅读器()
在 python 中,我们可以使用 csv 模块来处理 csv 文件。为了将 csv 文件读入字典列表,我们将使用csv.DictReader()
方法创建一个csv.DictReader
对象。在创建了DictReader
对象之后,我们可以使用以下步骤从 csv 文件创建一个字典列表。
- 首先,我们将在读取模式下使用
open()
函数打开 csv 文件。open()
函数将文件名作为它的第一个输入参数,将文字“r”作为它的第二个输入参数,以表明文件是以读取模式打开的。执行后,它返回一个包含 csv 文件的 file 对象。 - 从
open()
函数获得文件对象后,我们将使用csv.DictReader()
函数创建一个DictReader
对象。csv.DictReader()
函数将文件对象作为其输入参数,并返回一个DictReader
对象。 DictReader
对象作为迭代器工作,包含 csv 文件的每一行作为字典。在字典中,键由 csv 文件的列名组成,而与键相关联的值是行中特定列中的值。- 要将 csv 文件读入字典列表,我们将首先创建一个空列表。之后,我们将使用 for 循环将每个字典从
DictReader
对象添加到列表中。在执行 for 循环之后,我们将获得整个 csv 文件作为字典列表。 - 不要忘记在程序结束时使用
close()
方法关闭文件。
使用DictReader()
方法和 for 循环将 csv 读入字典列表的程序如下。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.DictReader(myFile)
myList = list()
for dictionary in reader:
myList.append(dictionary)
print("The list of dictionaries is:")
print(myList)
输出:
The list of dictionaries is:
[{'Roll': '1', 'Name': 'Aditya', 'Language': 'Python'}, {'Roll': '2', 'Name': 'Sam', 'Language': ' Java'}, {'Roll': '3', 'Name': ' Chris', 'Language': ' C++'}]
除了使用 for 循环,还可以使用 list()
构造函数将DictReader
对象转换成一个列表,如下所示。
import csv
myFile = open('Demo.csv', 'r')
reader = csv.DictReader(myFile)
myList = list(reader)
print("The list of dictionaries is:")
print(myList)
输出:
The list of dictionaries is:
[{'Roll': '1', 'Name': 'Aditya', 'Language': 'Python'}, {'Roll': '2', 'Name': 'Sam', 'Language': ' Java'}, {'Roll': '3', 'Name': ' Chris', 'Language': ' C++'}]
结论
在本文中,我们讨论了如何将 csv 文件读入 python 中的字典列表。要了解更多关于列表的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
用 Python 逐行读取文件
原文:https://www.pythonforbeginners.com/basics/read-file-line-by-line-in-python
文件操作在各种任务中至关重要。在本文中,我们将讨论如何在 python 中逐行读取文件。
使用 readline()方法读取文件
Python 为我们提供了readline()
方法来读取文件。要读取文件,我们将首先在读取模式下使用open()
功能打开文件。open()
函数将文件名作为第一个输入参数,将文字“r”作为第二个输入参数,表示文件以读取模式打开。执行后,它返回包含该文件的 file 对象。
得到 file 对象后,我们可以使用readline()
方法来读取文件。在 file 对象上调用readline()
方法时,返回文件中当前未读的行,并将迭代器移动到文件中的下一行。
为了逐行读取文件,我们将使用 readline()
方法读取文件中的每一行,并在 while 循环中打印出来。一旦readline()
方法到达文件的末尾,它将返回一个空字符串。因此,在 while 循环中,我们还将检查从文件中读取的内容是否为空字符串,如果是,我们将从 for 循环中退出。
使用readline()
方法读取文件的 python 程序如下。
myFile = open('sample.txt', 'r')
print("The content of the file is:")
while True:
text = myFile.readline()
if text == "":
break
print(text, end="")
myFile.close()
输出:
The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
建议文章:使用 C# |点网核心| SSH.NET 将文件上传到 SFTP 服务器
使用 readlines()方法在 Python 中逐行读取文件
在 python 中,我们可以使用readlines()
方法来读取文件,而不是使用 readline()
方法。当在 file 对象上调用readlines()
方法时,它返回一个字符串列表,其中列表中的每个元素都是文件中的一行。
打开文件后,我们可以使用readlines()
方法获得文件中所有行的列表。之后,我们可以使用一个 for 循环来逐个打印文件中的所有行,如下所示。
myFile = open('sample.txt', 'r')
print("The content of the file is:")
lines = myFile.readlines()
for text in lines:
print(text, end="")
myFile.close()
输出:
The content of the file is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
结论
在本文中,我们讨论了在 python 中逐行读取文件的两种方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
从 CSV 文件中读取特定列
原文:https://www.pythonforbeginners.com/basics/read-specific-columns-from-csv-file
CSV 文件是在文件系统中存储表格数据的最流行的方式。有时 csv 文件可以包含我们不需要分析的多个列。在本文中,我们将讨论如何用 python 从 csv 文件中读取特定的列。
使用 Pandas Dataframe 从 CSV 文件中读取特定列
为了用 python 读取 csv 文件,我们使用 pandas 模块中提供的read_csv()
方法。read_csv()
方法将 csv 文件的名称作为其输入参数。执行后,read_csv()
方法返回包含 csv 文件数据的 dataframe。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
如您所见, read_csv()
方法返回包含 csv 文件所有列的数据帧。为了从数据帧中读取特定的列,我们可以使用列名作为索引,就像我们从列表中获取元素一样。为此,我们可以简单地将列名传递给 dataframe 后面的方括号,如示例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
specific_column=df["Name"]
print("The column is:")
print(specific_column)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column is:
0 Aditya
1 Sam
2 Chris
3 Joel
Name: Name, dtype: object
要从 dataframe 中读取多个列,我们可以传递方括号中的列名列表,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
specific_columns=df[["Name","Roll"]]
print("The column are:")
print(specific_columns)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column are:
Name Roll
0 Aditya 1
1 Sam 2
2 Chris 3
3 Joel 4
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用“usecols”参数从 CSV 文件中读取特定列
读取整个数据帧并从数据帧中提取列不符合我们的目的。在上面的方法中,我们还将不需要的列读入数据帧。之后,我们正在阅读具体的栏目。我们可以通过在read_csv()
方法中使用‘usecols
’参数来避免整个过程。为了从 csv 文件中读取特定的列,我们将把要读取的列的列表作为输入参数传递给'usecols
'参数。执行后,read_csv()
方法返回包含特定列的 dataframe,如下例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv",usecols=["Name"])
print("The dataframe is:")
print(df)
输出:
The dataframe is:
Name
0 Aditya
1 Sam
2 Chris
3 Joel
正如您在上面看到的,我们已经使用'usecols
'参数从 csv 文件中读取了特定的列。
结论
在本文中,我们讨论了如何从 csv 文件中读取特定的列。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中字典理解的文章。你可能也会喜欢这篇关于 python 的列表理解的文章。
用 Python 读写文件
原文:https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
概观
当您使用 Python 时,不需要为了读写文件而导入库。它是在语言中自然处理的,尽管是以一种独特的方式。下面,我们概述了用 Python 读写文件的简单步骤。
首先你需要做的是使用 python 内置的 打开 文件函数得到一个 文件对象 。
打开 功能打开一个文件。很简单。这是用 python 读写文件的第一步。
当你使用 打开 函数时,它返回一个叫做 的文件对象 。 文件对象 包含方法和属性,可用于收集关于您打开的文件的信息。它们也可以用来操作所述文件。
例如, 文件对象 的 模式 属性告诉你文件是以哪种模式打开的。而 名称 属性告诉你文件的名称。
你必须明白一个 文件 和 文件对象 是两个完全独立却又相关的东西。
文件类型
您可能知道的文件在 Python 中略有不同。
例如,在 Windows 中,文件可以是由用户/操作系统操作、编辑或创建的任何项目。这意味着文件可以是图像、文本文档、可执行文件和 excel 文件等等。大多数文件都是通过保存在单独的文件夹中来组织的。
Python 中的文件分为文本文件和二进制文件,这两种文件类型之间的区别很重要。
文本文件由一系列行组成,每一行都包含一系列字符。这就是你所知道的代码或语法。
每一行都以一个特殊字符结束,称为 EOL 或行尾字符。有几种类型,但最常见的是逗号{,}或换行符。它结束当前行,并告诉解释器新的一行已经开始。
也可以使用反斜杠字符,它告诉解释器斜杠后面的下一个字符应该被当作新的一行。当您不想在文本本身而是在代码中开始一个新行时,这个字符很有用。
二进制文件是非文本文件的任何类型的文件。由于其性质,二进制文件只能由知道或理解文件结构的应用程序处理。换句话说,它们必须是可以读取和解释二进制的应用程序。
用 Python 读取文件
在 Python 中,使用 open() 方法读取文件。这是 Python 的内置方法之一,用于打开文件。
open() 函数有两个参数:文件名和文件打开模式。文件名指向文件在你电脑上的路径,而文件打开模式用来告诉 open() 函数我们计划如何与文件交互。
默认情况下,文件打开模式设置为只读,这意味着我们只有打开和检查文件内容的权限。
在我的电脑上有一个名为 PythonForBeginners 的文件夹。那个文件夹里有三个文件。一个是名为 emily_dickinson.txt 的文本文件,另外两个是 python 文件:read.py 和 write.py。
该文本文件包含以下由诗人艾米莉·狄金森所写的诗。也许我们正在做一个诗歌程序,并把我们的诗歌作为文件储存在电脑上。
从未成功的人认为成功是最甜蜜的。
领悟一种甘露
需要最迫切的需要。
所有的紫主持人
中没有一个人今天接过了
的旗帜能把
的定义说得如此清晰的胜利
随着他的战败,
在谁的禁耳上
远处胜利的旋律
迸发出极度痛苦和清晰。
在我们对诗歌文件的内容做任何事情之前,我们需要告诉 Python 打开它。read.py 文件包含阅读这首诗所需的所有 python 代码。
任何文本编辑器都可以用来编写代码。我使用的是 Atom 代码编辑器,这是我使用 python 时的首选编辑器。
This screenshot shows my setup in Atom.
# read.py
# loading a file with open()
myfile = open(“emily_dickinson.txt”)
# reading each line of the file and printing to the console
for line in myfile:
print(line)
我用 Python 注释解释了代码中的每一步。点击这个链接了解更多关于什么是 Python 注释的信息。
上面的例子说明了如何在 Python 中使用一个简单的循环来读取文件的内容。
在读取文件时,Python 会在幕后处理这些麻烦。通过使用命令提示符或终端导航到该文件,然后键入“python”后跟文件名,来运行脚本。
Windows 用户:在命令提示符下使用 python 关键字之前,您需要设置环境变量。当您安装 Python 时,这应该是自动发生的,但如果没有,您可能需要手动进行。
>python read.py
由 open() 方法提供的数据通常存储在一个新的变量中。在这个例子中,诗歌的内容存储在变量“myfile”中。
创建文件后,我们可以使用 for 循环读取文件中的每一行,并将其内容打印到命令行。
这是如何用 Python 打开文件的一个非常简单的例子,但是学生应该知道 open() 方法非常强大。对于一些项目来说,这将是用 Python 读写文件所需要的唯一东西。
用 Python 写文件
在我们可以用 Python 写一个文件之前,必须先用不同的文件打开模式打开它。我们可以通过提供带有特殊参数的 open() 方法来做到这一点。
在 Python 中,使用 open() 方法写入文件。您需要传递一个文件名和一个特殊字符,告诉 Python 我们打算写入该文件。
将以下代码添加到 write.py。我们将告诉 Python 查找名为“sample.txt”的文件,并用新消息覆盖其内容。
# open the file in write mode
myfile = open(“sample.txt”,’w’)
myfile.write(“Hello from Python!”)
向 open() 方法传递‘w’告诉 Python 以写模式打开文件。在这种模式下,当写入新数据时,文件中已有的任何数据都会丢失。
如果文件不存在,Python 将创建一个新文件。在这种情况下,程序运行时将创建一个名为“sample.txt”的新文件。
使用命令提示符运行程序:
>python write.py
Python 也可以在一个文件中写入多行。最简单的方法是使用 writelines() 方法。
# open the file in write mode
myfile = open(“sample.txt”,’w’)
myfile.writelines(“Hello World!”,”We’re learning Python!”)
# close the file
myfile.close()
我们还可以使用特殊字符将多行写入一个文件:
# open the file in write mode
myfile = open("poem.txt", 'w')
line1 = "Roses are red.\n"
line2 = "Violets are blue.\n"
line3 = "Python is great.\n"
line4 = "And so are you.\n"
myfile.write(line1 + line2 + line3 + line4)
使用字符串连接使得 Python 能够以多种方式保存文本数据。
然而,如果我们想避免覆盖文件中的数据,而是追加或更改它,我们必须使用另一种文件打开模式打开文件。
文件打开模式
默认情况下,Python 将以只读模式打开文件。如果我们想做除了读取文件之外的任何事情,我们需要手动告诉 Python 我们打算用它做什么。
- r’–读取模式:这是 open() 的默认模式。文件被打开,指针位于文件内容的开头。
- w '–写入模式:使用此模式将覆盖文件中的任何现有内容。如果给定的文件不存在,将创建一个新文件。
- r+'–读/写模式:如果您需要同时读写文件,请使用此模式。
- a '–追加模式:在这种模式下,用户可以追加数据,而不会覆盖文件中任何已经存在的数据。
- a+'–追加和读取模式:在这种模式下,您可以读取和追加数据,而不会覆盖原始文件。
- x '–独占创建模式:该模式仅用于创建新文件。如果您事先知道要写入的文件不存在,请使用此模式。
注意:这些例子假设用户正在处理文本文件类型。如果意图是读取或写入二进制文件类型,则必须向 open() 方法传递一个额外的参数:字符“b”。
# binary files need a special argument: ‘b’
binary_file = open(“song_data.mp3”,’rb’)
song_data = binary_file.read()
# close the file
binary_file.close()
用 Python 关闭文件
在 Python 中打开一个文件后,重要的是在完成后关闭它。关闭文件可以确保程序无法再访问其内容。
用 close() 方法关闭一个文件。
# open a file
myfile = open(“poem.txt”)
# an array to store the contents of the file
lines = []
For line in myfile:
lines.append(line)
# close the file
myfile.close()
For line in liens:
print(line)
打开其他文件类型
open() 方法可以读写许多不同的文件类型。我们已经看到了如何打开二进制文件和文本文件。Python 还可以打开图像,允许您查看和编辑它们的像素数据。
在 Python 可以打开图像文件之前,必须安装 Pillow 库(Python 图像库)。使用 pip 安装这个模块是最简单的。
pip install Pillow
安装了 Pillow 后,Python 可以打开图像文件并读取其内容。
From PIL import Image
# tell Pillow to open the image file
img = Image.open(“your_image_file.jpg”)
img.show()
img.close()
Pillow 库包含强大的图像编辑工具。这使得它成为最受欢迎的 Python 库之一。
With 语句
您还可以使用带有语句的来处理文件对象。它旨在当您处理代码时提供更清晰的语法和异常处理。这解释了为什么在适当的地方使用 with 语句是一种好的做法。
使用这种方法的一个好处是,任何打开的文件都会在您完成后自动关闭。这样在清理过程中就不用太担心了。
使用 with 语句打开文件:
***with open(“filename”) as file:* **
现在你明白了如何调用这个语句,让我们来看几个例子。
***with open(“poem.txt”) as file: * **
***data = file.read()* **
***do something with data* **
使用此语句时,还可以调用其他方法。例如,您可以对文件对象执行类似循环的操作:
**w*ith open(“poem.txt”) as f:* **
***for line in f:* **
***print line,* **
你还会注意到,在上面的例子中,我们没有使用“”file . close()”方法,因为 with 语句会在执行时自动调用它。这真的让事情变得简单多了,不是吗?
在文本文件中拆分行
作为最后一个例子,让我们探索一个独特的函数,它允许您从文本文件中分割行。这样做的目的是,每当解释器遇到一个空格字符时,就分割变量数据中包含的字符串。
但是仅仅因为我们要用它来在一个空格字符后分行,并不意味着这是唯一的方法。实际上,你可以使用任何字符来拆分你的文本,比如冒号。
执行此操作的代码(也使用 with 语句)是:
***with* *open(**“**hello.text**”, “r”) as f:***
***data =* *f.readlines**()***
***for line in data:***
***words =* *line.split**()***
***print words***
如果您想使用冒号而不是空格来拆分文本,只需将 line.split()改为 line.split("😊。
其输出将是:
***[“hello”, “world”, “how”, “are”, “you”, “today?”]***
***[“today”, “is”, “Saturday”]***
以这种方式显示单词的原因是因为它们以数组的形式存储和返回。使用拆分功能时,请务必记住这一点。
结论
在 Python 中读写文件涉及到对 open() 方法的理解。通过利用这种方法的通用性,可以在 Python 中读取、写入和创建文件。
Python 文件可以是文本文件,也可以是二进制文件。还可以使用枕头模块打开和编辑图像数据。
一旦一个文件的数据被加载到 Python 中,实际上可以用它做的事情是无穷无尽的。程序员经常处理大量的文件,使用程序自动生成它们。
与任何课程一样,在所提供的空间内只能涵盖这么多内容。希望您已经掌握了足够的知识,可以开始用 Python 读写文件。