[英]How to compare two lists in python?
How to compare two lists in python?如何比较python中的两个列表?
date = "Thu Sep 16 13:14:15 CDT 2010"
sdate = "Thu Sep 16 14:14:15 CDT 2010"
dateArr = [] dateArr = date.split()
sdateArr = [] sdateArr = sdate.split()
Now I want to compare these two lists.现在我想比较这两个列表。 I guess split returns a list.我猜 split 返回一个列表。 We can do simple comparision in Java like dateArr[i] == sdateArr[i]
, but how can we do it in Python?我们可以在 Java 中进行简单的比较,例如dateArr[i] == sdateArr[i]
,但是我们如何在 Python 中进行比较呢?
You could always do just:你总是可以这样做:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]
a==b #returns False
a==c #returns False
a==d #returns True
a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']
# if you care about order
a == b # True
a == c # False
# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True
By casting a
, b
and c
as a set, you remove duplicates and order doesn't count.通过将a
、 b
和c
强制转换为一组,您可以删除重复项并且订单不计算在内。 Comparing sets is also much faster and more efficient than comparing lists.比较集合也比比较列表更快、更有效。
If you mean lists, try ==
:如果您的意思是列表,请尝试==
:
l1 = [1,2,3]
l2 = [1,2,3,4]
l1 == l2 # False
If you mean array
:如果你的意思是array
:
l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False
If you want to compare strings (per your comment):如果你想比较字符串(根据你的评论):
date_string = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False
Given the code you provided in comments, I assume you want to do this:鉴于您在评论中提供的代码,我假设您想这样做:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false
The split
-method of the string returns a list.字符串的split
方法返回一个列表。 A list in Python is very different from an array. Python 中的列表与数组非常不同。 ==
in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. ==
在这种情况下对两个列表进行逐元素比较,如果它们的所有元素都相等并且元素的数量和顺序相同,则返回。 Read the documentation .阅读文档。
for i in arr1:
if i in arr2:
return 1
return 0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0
From your post I gather that you want to compare dates, not arrays.从您的帖子中我了解到您想比较日期,而不是数组。 If this is the case, then use the appropriate object: a datetime
object.如果是这种情况,则使用适当的对象: datetime
对象。
Please check the documentation for the datetime module .请查看datetime 模块的文档。 Dates are a tough cookie.日期是一个艰难的饼干。 Use reliable algorithms.使用可靠的算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.