在 Python 中创建包含重复项的列表

当我们从数据中提取信息时,我们经常会遇到相同的值。我们可以通过多种方法消除重复项以创建唯一的数组。或者我们也可以确定哪些元素有副本,并创建一个包含重复项的列表。

在本教程中,我们将了解如何识别列表中多次出现的元素,然后使用这些元素创建另一个新列表。

在 python 中,识别列表中的重复项比在其他语言中相对容易。它可以通过内置函数或用户定义的代码块来完成。

什么是Python列表?

Python列表一种类似于其他语言中的数组的数据结构。Python 列表对于数据操作和保留信息非常有用。Python 列表是除集合、元组和字典之外最流行的 Python 数据类型之一。列表是不可变的数据类型,也就是说,它们的值可以随时随地显式更改。

Python 列表还用于实现矩阵和数值 Python 数组以进行科学计算。列表数据类型拥有 Python 中最大的内置函数库之一。使用像count()和这样的函数append() ,我们可以轻松识别和截断同一元素的副本。

建议:Python 数据类型

如何创建包含重复项的列表

我们需要解决的主要问题是识别列表中哪些元素有另一个副本。这可以通过两种方式完成:

  • 手动编写一段代码,使用 for 循环逐个遍历列表中的元素,然后查找重复项。
  • 或者,借助内置函数来实现上述技术。

让我们探索这两种方法,您可以使用您认为适合您的程序的任何方法。

方法一:在python中手动遍历列表

在这种方法中,我们必须使用for循环手动遍历列表的元素并相应地找到匹配项。然后我们必须使用if语句检查每个元素的出现情况。最后,我们将仅附加那些在名为 的新列表中多次出现的元素duplicate我们看一下代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# assigning two list object
 
(lst, duplicate) = ([], [])  # lst is for original and duplicate is for duplicates list
 
# declaring size of list
N = int(input('Enter the size of list='))
 
# input for list
for i in range(N):
    ele = input('Enter the ' + str(i + 1) + ' element= ')
    lst.append(ele)
 
# displaying the original list
print ('The original list is=', lst)
 
# traversing through the list
for i in range(N):
    check = lst[i]
 
  # check for duplicates
    for j in range(i + 1, N):
        if check == lst[j]:
            duplicate.append(check)
 
print ('the list with the elements which have more than one instance in the original=', duplicate)

代码的第一部分接收列表的用户输入,然后它将识别重复项,然后使用在原始列表中具有多个副本的元素创建一个列表。运行代码并提供输入后,我们得到以下输出:

Enter the size of list=5
Enter the 1 element= hi
Enter the 2 element= hi
Enter the 3 element= bye
Enter the 4 element= bye
Enter the 5 element= hello
The original list is= ['hi', 'hi', 'bye', 'bye', 'hello']
the list with the elements which have more than one instance in the original= ['hi', 'bye']
遍历列表并识别副本

阅读更多内容:从 Python 列表中提取元素的 5 种简单方法。

方法2:使用count()函数

count()函数计算集合或列表中特定元素的实例数。我们还可以显式地将另一种数据类型转换为列表,因此在这种方法中该功能也派上用场。

#assigning two list object
lst,duplicate=[],[] #lst is for original and duplicate is for duplicates list
#declaring size of list
N=int(input("Enter the size of list="))
#input for list
for i in range(N):
    ele=input("Enter the "+str(i+1)+" element= ")
    lst.append(ele)
#displaying the original list
print("The original list is=",lst)
duplicate = list({x for x in lst if lst.count(x) > 1})
print("The list with elements whose duplicates exist=",duplicate)

输出将是:

Enter the size of list=5
Enter the 1 element= hi
Enter the 2 element= yo
Enter the 3 element= yo
Enter the 4 element= bro
Enter the 5 element= no
The original list is= ['hi', 'yo', 'yo', 'bro', 'no']
The list with elements whose duplicates exist= ['yo']
使用 Count() 函数

结论

总之,在本教程中,我们了解了识别列表中重复项的两种方法。当从不同来源收集数据时,我们必须检查大型数组中单个元素的实例。在第一种方法中,实现是以更机械的方式完成的,而在第二个示例中,我们使用了 python 以内置模块的形式提供的特权。要了解有关 python 列表的更多信息,请单击此处