在python中,当列表等于矩阵的一行时执行命令
如果下面列表中的所有3个值都等于矩阵一行中的3个值中的任何一个,我希望它打印“hello”在python中,当列表等于矩阵的一行时执行命令,python,list,matrix,Python,List,Matrix,如果下面列表中的所有3个值都等于矩阵一行中的3个值中的任何一个,我希望它打印“hello” #if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string. x = [1, 2, 3] y = [ [1, 2, 3], [4, 5
#if x is equal to the 1st line of the matrix I want it to print hello. If x is equal to the 2nd part and not the 1st I still want it to print the same string.
x = [1, 2, 3]
y = [
[1, 2, 3],
[4, 5, 6],
[3, 4, 5],
[7, 8, 9]
]
if x == (y):
print('hello')
如上所示,x列表值等于矩阵中的一行,但它不会打印hello。我怎样才能让程序做到这一点呢 在正常情况下,您只需使用-
if x in y:
print('hello')
如果您想以任何顺序检查您的唯一值,那么您需要首先进行排序,如下所示
x = [1, 2, 3]
y = [
[1, 3, 2],
[4, 5, 6],
[3, 4, 5],
[7, 8, 9]
]
x = sorted(x)
for i in range(len(y)):
y[i] = sorted(y[i])
if x in y:
print('hello')
您正在进行的比较-
x==(y)
失败,因为(y)
的计算结果为y
,而x==y
为假(因为y
是一个嵌套列表)
您要做的是迭代行:
x = [1,2,3]
y = [
[1, 2, 3],
[4, 5, 6],
[3, 4, 5],
[7, 8, 9]
]
for yi in y:
if x == yi:
print("Hello")
对于给定的输入,这会打印Hello一次。如果[1,2,3]
多次出现,它会在每次找到Hello时打印Hello
注意,这假设
[1,2,3]!=[3,2,1]
(这是Python内部假定的)。如果顺序不重要,你必须调整它。这种测试有一个内置函数,叫做any
,它检查一系列值是否为真。我们还没有想要的真值或假值,所以我们需要创建它们。策略是将y
列表中的值转换为一个真实值,该值指示该值是否等于x
。我们可以通过生成器表达式优雅地执行此操作:
any(row == x for row in y)
它的意思正是它听起来的样子:如果行值中的任何都是==x
,那么考虑的行值是在y
中,OP没有说明元素的顺序,因此没有理由假设需要排序。