Python 查找元组中列表的数量

Python 元组是有序且不可更改的。但它也可以由列表作为其元素组成。给定一个由列表组成的元组,让我们找出元组中有多少个列表。

使用 len()

在这种方法中,我们将应用 len 函数。 len() 函数将给出元组元素列表的数量。

示例

复制代码
tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])

print("tupA 中的列表数量:\n" , len(tupA))
print("tupB 中的列表数量:\n" , len(tupB))

输出

运行上述代码得到以下结果 −

复制代码
tupA 中的列表数量:
2
tupB 中的列表数量:
3

使用 UDF

如果我们必须反复使用此操作,我们可以很好地定义一个函数来检查我们传递的元素是否是元组。然后应用 len 函数计算其中列出的元素数量。

示例

复制代码
tupA = (['a', 'b', 'x'], [21,19])
tupB = (['n', 'm'], ['z','y', 'x'], [3,7,89])

def getcount(tupl):
   if isinstance(tupl, tuple):
      return len(tupl)
   else:
      pass

print("tupA 中的列表数量:\n" , getcount(tupA))
print("tupA 中的列表数量:\n" , getcount(tupB))

输出

运行上述代码得到以下结果 −

复制代码
tupA 中的列表数量:
2
tupA 中的列表数量:
3

相关文章


有用资源

相关推荐
孟健3 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞5 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽7 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程12 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪12 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook12 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python