在python数据分析中,当我们需要比较两个列表并找出它们是否具有相同元素或没有相同含义时,我们可能会遇到这种情况。
listA = ['Mon','Tue','Wed','Thu'] listB = ['Mon','Wed','Tue','Thu'] # Given lists print("Given listA: ",listA) print("Given listB: ",listB) # Sort the lists listA.sort() listB.sort() # Check for equality if listA == listB: print("Lists are identical") else: print("Lists are not identical")
输出结果
运行上面的代码给我们以下结果-
Given listA: ['Mon', 'Tue', 'Wed', 'Thu'] Given listB: ['Mon', 'Wed', 'Tue', 'Thu'] Lists are identical
来自集合的计数器功能可以帮助我们找到列表中每个项目的出现次数。在下面的示例中,我们还采用了两个重复元素。如果两个列表中每个元素的频率相等,则我们认为列表是相同的。
import collections listA = ['Mon','Tue','Wed','Tue'] listB = ['Mon','Wed','Tue','Tue'] # Given lists print("Given listA: ",listA) print("Given listB: ",listB) # Check for equality if collections.Counter(listA) == collections.Counter(listB): print("Lists are identical") else: print("Lists are not identical") # Checking again listB = ['Mon','Wed','Wed','Tue'] print("Given listB: ",listB) # Check for equality if collections.Counter(listA) == collections.Counter(listB): print("Lists are identical") else: print("Lists are not identical")
输出结果
运行上面的代码给我们以下结果-
Given listA: ['Mon', 'Tue', 'Wed', 'Tue'] Given listB: ['Mon', 'Wed', 'Tue', 'Tue'] Lists are identical Given listB: ['Mon', 'Wed', 'Wed', 'Tue'] Lists are not identical