我试图比较Python中的两个列表,检查它们是否相同。问题是,这两个列表都可以包含重复的元素,为了被认为是相等的,它们需要有相同数量的重复元素。
目前,我已经“解决”了这一问题,方法是创建两个列表的副本,如果两个列表相等,则从它们中删除一个元素:
def equals(v1: Vertex, v2: Vertex) -> bool:
# also checks if neighbourhoods are the same size
if v1.label == v2.label:
# copy the neighbourhoods to prevent
#for 1d lists
x = [1,2,3]
y = [1,2,3]
print([True if x[i]==y[i] else False for i in range(len(x))])
#for 2d lists
d=[[0,0,0,0],[0,0,0,0],[0,0,0,0]]
e=[[0,0,1,0],[0,0,0,0],[0,0,0,0]]
for i in range(0,len(d)):
for j in range(0,len(d[i])):
if d[i][j]==e[i][j]:
continue
许多教程都指出,==比较运算符是值相等的,就像在这个中,引用如下:
==代表价值相等。当您想知道两个对象的值是否相同时,请使用它。
is用于引用相等。当您想知道两个引用是否引用同一个对象时,请使用它。
但是,我发现Python 说:
x==y打电话给x.__eq__(y)。默认情况下,object通过使用is实现__eq__(),在错误比较的情况下返回NotImplemented:True if x is y else NotImplemented。
==操作符的默认行为似乎是像is操作符一样比较引用质量,这与这些教程的说法相矛盾。
那么,我到底应该使用==做什
如何在python中检查一个列表是否是另一个列表的一部分,并保持顺序。示例: a = [3, 4, 1, 2, 5]
b = [4, 1, 2]
Answer is True
a = [3, 4, 1, 0, 2, 5]
b = [4, 1, 2]
Answer is False as the order is not matched
我想使用两个for循环来迭代两个大的列表,但是不会发生任何事情。以下是代码
pfam = open(r'D:\RPS_data\pfam_annotations.tbl', 'r')
number = []
description = []
for j in pfam:
number.append(j.split('\t')[0])
description.append(j.split('\t')[-2])
print len(number),len(description)
for j in number:
我想返回两个字典列表的True在成员上是相等的(成员是每个字典的内容,不顾列表的顺序),否则返回False。在python中做这件事的好方法是什么?
如果a= dict1,dict2和b = dict2,dict1,那么a等于b(符1和符2的键和值必须匹配)。
我的方式是:
def _compare(self, a,b):
if len(a) != len(b):
return False
for d in a:
if d in b:
continue
el
是否可以先按employee对象的薪水排序,如果两个对象的薪水相等,然后使用可比较和比较器接口按名称进行比较?
例如,我有一个Employee类,如下所示
public class Employee{
private int salary;
private int name;
public Employee(salary,name){
this.salary = salary;
this.name = name;
}
//...........getter methods...........
}
现在假设我们有一个Emp
我有一件非常奇怪的事情发生,其中两个列表显然是相等的,但Python并不认为它们是相等的。在这里,您可以看到我正在使用的字典元素的IPython控制台输出:
In [251]: saveDict['data']['hpSH']['manifold_type'] Out[251]: ['duct', 'pipe']
然后,当我检查这个相同的字典元素是否等于“管道”和“管道”列表时,它会说它不是:
In [252]: ['duct', 'pipe'] is saveDict['d