master>views.py
# Create your views here.
def compare_2_list():
old_list = ['A001', 'B002', 'C003']
new_list = ['C003', 'A001', 'B002']
s1 = set(old_list)
s2 = set(new_list)
if s1 == s2:
print('s1 == s2')
print(s1)
print(s2)
else:
print('s1 != s2')
if old_list == new_list:
print('old_list == new_list')
else:
print('old_list != new_list')
old_list.sort()
new_list.sort()
if old_list == new_list:
print('old_list == new_list after sort')
else:
print('old_list != new_list after sort')
执行结果
(venv) D:\PycharmProjects\djangoTutorial>python manage.py shell
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from master.views import compare_2_list
>>> compare_2_list()
s1 == s2
{'B002', 'A001', 'C003'}
{'B002', 'A001', 'C003'}
old_list != new_list
old_list == new_list after sort
['A001', 'B002', 'C003']
>>>
collection保存数据的形式:format <value>:<frequency>,比较也和顺序无关。
import collections
def compare_list_by_collection():
old_list1 = ['A001', 'B002', 'C003', 'B002']
old_list2 = ['A001', 'B002', 'C003']
new_list = ['C003', 'A001', 'B002']
if collections.Counter(old_list1) == collections.Counter(new_list):
print("old_list1 and new_list are the same")
else:
print("old_list1 and new_list are not the same")
if collections.Counter(old_list2) == collections.Counter(new_list):
print("old_list2 and new_list are the same")
else:
print("old_list2 and new_list are not the same")
print(collections.Counter(old_list1).items()) # dict_items([('A001', 1), ('B002', 2), ('C003', 1)])
print(collections.Counter(old_list2).items()) # dict_items([('A001', 1), ('B002', 1), ('C003', 1)])
print(collections.Counter(new_list).items()) # dict_items([('C003', 1), ('A001', 1), ('B002', 1)])
print(collections.Counter(old_list1)) # Counter({'B002': 2, 'A001': 1, 'C003': 1})
print(collections.Counter(old_list2)) # Counter({'A001': 1, 'B002': 1, 'C003': 1})
print(collections.Counter(new_list)) # Counter({'C003': 1, 'A001': 1, 'B002': 1})
执行结果
(venv) D:\PycharmProjects\djangoTutorial>python manage.py shell
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from master.views import compare_list_by_collection
>>> compare_list_by_collection()
old_list1 and new_list are not the same
old_list2 and new_list are the same
dict_items([('A001', 1), ('B002', 2), ('C003', 1)])
dict_items([('A001', 1), ('B002', 1), ('C003', 1)])
dict_items([('C003', 1), ('A001', 1), ('B002', 1)])
Counter({'B002': 2, 'A001': 1, 'C003': 1})
Counter({'A001': 1, 'B002': 1, 'C003': 1})
Counter({'C003': 1, 'A001': 1, 'B002': 1})
>>>
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。