python查看列表一共有多少元素_如何获取Python中的列表中的元素的数量?

文章目录

items = []

items.append(“apple”)

items.append(“orange”)

items.append(“banana”)

# FAKE METHOD::

items.amount() # Should return 3

如何获取列表中的元素数量?

` len()代码>功能可以在Python中使用很多类型 -

内置类型和库类型。

>>> len([1,2,3])

3

要查找列表的大小,请使用内置函数len:

items = []

items.append("apple")

items.append("orange")

items.append("banana")

现在:

len(items)

返回3。

From the

LEN(S)

Return the length (the number of items) of an object. The argument may be a

sequence (such as a string, bytes, tuple, list, or range) or a collection

(such as a dictionary, set, or frozen set).

len 是通过 len `从数据模型docs:

`对象.LEN(个体)

Called to implement the built-in function len(). Should return the length

of the object, an integer >= 0. Also, an object that doesnat define a

__nonzero__() [in Python 2 or __bool__() in Python 3] method and whose

__len__() method returns zero is considered to be false in a Boolean

context.

我们还可以看到__ len __是列表方法:

items.__len__()

返回3。

Builtin types you can get the len (length) of

实际上,我们看到我们可以得到所有描述类型的信息:

>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,

xrange, dict, set, frozenset))

True

Do not use len as a value for a condition

不要做:

if len(items):

...

相反,做:

if items:

...

我解释为什么在这里但简而言之,它更具可读性和更高性能。

未经作者同意,本文严禁转载,违者必究!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值