检查列表中的所有元素在Python中是否相同

Here, we are implementing a python program to check whether all elements of a list are the same or not?

在这里,我们正在实现一个python程序来检查列表中的所有元素是否相同?

We can use [1:] and [:-1] to compare all the elements in the given list.

我们可以使用[1:]和[:-1]比较给定列表中的所有元素。

Program:

程序:

# function to check elements
def check_equal(a):
  return a[1:] == a[:-1]

# lists
x = [10, 20, 30, 40,50]
y = [10, 20, 20, 20, 20]
z = [10, 10, 10, 10, 10]

# check how [1:] and [:-1] wors?
print("x: ", x)
print("x[1:]: ", x[1:])
print("x[:-1]: ", x[:-1])
print("check_equal(x): ",check_equal(x))
print()

print("y: ", y)
print("y[1:]: ", y[1:])
print("y[:-1]: ", y[:-1])
print("check_equal(y): ",check_equal(y))
print()

print("z: ", z)
print("z[1:]: ", z[1:])
print("z[:-1]: ", z[:-1])
print("check_equal(z): ",check_equal(z))
print()

Output

输出量

x:  [10, 20, 30, 40, 50]
x[1:]:  [20, 30, 40, 50]
x[:-1]:  [10, 20, 30, 40]
check_equal(x):  False

y:  [10, 20, 20, 20, 20]
y[1:]:  [20, 20, 20, 20]
y[:-1]:  [10, 20, 20, 20]
check_equal(y):  False

z:  [10, 10, 10, 10, 10]
z[1:]:  [10, 10, 10, 10]
z[:-1]:  [10, 10, 10, 10]
check_equal(z):  True


翻译自: https://www.includehelp.com/python/check-all-elements-of-a-list-are-the-same-or-not.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值