打印列表和目录

打印列表

listnum = [1,2,3,4,5,6]

方法1

for num in listnum:
    print(num)
    
打印结果:
1
2
3
4
5
6

方法2

for i in range(len(listnum)):
     print(listnum[i])
     
打印结果:同方法1

方法3

#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
for i,j in enumerate(listnum):
     print('第{}个是{}'.format(i,j))

打印结果:
第0个是11个是22个是33个是44个是55个是6

打印字典

dict = {
    
    '1':'one','2':'two','3':'three'}

方法1

for num in listnum:
    print(num)
    
打印结果:
{
    
    '1': 'one', '2': 'two', '3': 'three'}

方法2

for k, v in dict.items():
    print(k, v)
    
打印结果:
1 one
2 two
3 three

方法3

for k in dict:
    print(k, dict[k])
    
打印结果:同方法2

方法4

#依次打印key
for key in dict.keys():
    print('key = {}'.format(key))
#依次打印value
for value in dict.values():
    print('value = {}'.format(value))
    
打印结果:
key = 1
key = 2
key = 3
value = one
value = two
value = three

猜你喜欢

转载自blog.csdn.net/qq_36786467/article/details/108184194