查看变量的属性 dir(变量)

本文通过实例详细介绍了Python中zip()函数的使用方法,包括如何查看zip对象的属性及如何正确遍历并打印出zip对象的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例:

我们在网上查找zip用法,自己却打印不出结果:

import os
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = zip(a, b)
print(c)        #<zip object at 0x00000000038421C8>

这时候我们可以先看下c有哪些属性dir(变量名)

import os

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = zip(a, b)
print(c)        #<zip object at 0x00000000038421C8>
print(dir(c)) 
'''['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']'''

可以看到有__iter__属性,所以我们可以用遍历方式打印出来

import os

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = zip(a, b)
print(c)        #<zip object at 0x00000000038421C8>
print(dir(c)) #['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

for arg in c:
    print(arg)  #(1, 'a')  (2, 'b')  (3, 'c')

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值