在Python中用一个列表除以一个数字

数据是任何应用程序中最重要的部分。我们以不同的形式存储数据,如数组、列表和对象,并在不同的函数中使用它们来存储我们数据库中的所需数据。

本文将探讨一个列表除以一个数字的不同方法。我们将使用循环来迭代列表,将每个元素除以一个特定的数字,并将结果保存到另一个列表中。

在 Python 中使用for 循环来将一个列表除以一个数字

首先,我们将使用for 循环来执行这项任务。让我们看一个例子,在这个例子中,我们将创建一个数字的列表,然后用5 进行除法。

例子:

# python
listToDivide = [5,10,15,20,25,30,35,40,45,50]
print("List before dividing by 5: ",listToDivide)
newList = []
for items in listToDivide:
    new = items/5
    newList.append(int(new))
print("List after dividing by 5: ",newList)

输出:

Divide List Using for Loop

正如你在上面的例子中所看到的,我们可以很容易地使用for 循环将一个列表除以一个特定的数字。但是,如果我们想保存被该数字除以后没有剩余的数据呢?

让我们在下面的例子中使用这个概念。我们将制作两个不同的列表来保存有余数和无余数的数字。

例子:

# python
listToDivide = [3,5,7,10,13,15,17,20,23,25,29,30,33,35,37,40,41,45,47,50]
print("List before dividing by 5: ",listToDivide)
newIntList = []
newFloatList = []
for items in listToDivide:
    if items % 5 == 0:
        newIntList.append(int(items))
    else:
        newFloatList.append(items)
print("List of numbers divisible by 5: ",newIntList)
print("List of numbers not divisible by 5: ",newFloatList)

输出:

Divide List Using for Loop and Save Into 2 Lists

正如你在例子中所看到的,我们甚至可以使用这种技术,根据哪些数字可以除以和不可以除以一个特定的数字来分离数据。

在Python中使用while 循环来除以一个列表中的数字

现在,让我们来讨论另一种可以用来将一个列表除以一个数字的方法。在这个方法中,我们将使用一个while 循环。所以让我们用这个循环与我们在第一个例子中讨论的情况相同。

例子:

# python
listToDivide = [5,10,15,20,25,30,35,40,45,50]
print("List before dividing by 5: ",listToDivide)
newList = []
a = 0
while a < len(listToDivide):
    new = listToDivide[a]/5
    newList.append(int(new))
    a = a + 1
print("List after dividing by 5: ",newList)

输出:

Divide List Using while Loop

正如你所看到的,我们可以使用while 循环轻松地将一个列表除以一个特定的数字。其结果与for 循环中的结果相同。

现在,让我们在第二个例子中使用这个概念,通过使用while 循环来实现它,并根据元素是否能被数字整除,将结果保存在两个不同的列表中。

现在,让我们来看看如何使用while 循环来达到同样的目的。

例子:

# python
listToDivide = [3,5,7,10,13,15,17,20,23,25,29,30,33,35,37,40,41,45,47,50]
print("List before dividing by 5: ",listToDivide)
newIntList = []
newFloatList = []
a = 0
while a < len(listToDivide):
    if listToDivide[a] % 5 == 0:
        newIntList.append(int(listToDivide[a]))
        a = a + 1
    else:
        newFloatList.append(listToDivide[a])
        a = a + 1
print("List of numbers divisible by 5: ",newIntList)
print("List of numbers not divisible by 5: ",newFloatList)

输出:

Divide List Using while Loop and Save Into 2 Lists

正如你所看到的,我们可以用forwhile 循环实现同样的逻辑,并得到同样的结果。循环使我们更容易遍历每一个列表元素,并按我们的意愿对其执行任何任务。

在 Python 中使用列表理解法将一个列表除以一个数字

另一种将一个列表除以一个数字的方法是使用列表理解法。这种方法是单行方法;我们在一行中写代码,这样就可以执行。

在我们的第二个例子中,这是一个非常复杂的方法,在这个例子中,我们将根据元素是否能被一个特定的数字整除来分离它们。

因此,让我们使用列表理解法来将一个列表除以一个数字,如下所示。

例子:

# python
listToDivide = [5,10,15,20,25,30,35,40,45,50]
print("List before dividing by 5: ",listToDivide)
newList = []
[newList.append(int(i/5)) for i in listToDivide]
print("List after dividing by 5: ",newList)

输出:

Divide List Using List Comprehension

从上面的例子可以看出,我们也可以用列表理解法来除以一个数字。