栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python中的遍历

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python中的遍历

一、测试文件夹及文件

 

二、代码
import  os
print('solution 1多层次遍历路径##############')
res_dir=os.path.abspath(os.path.dirname(__file__))
for root, dirs, files in os.walk(res_dir):
    print('root',root)
    print('dirs', dirs)
    print('files', files)

print('solution 2单层遍历某路径##############')
filelist=os.listdir()
print(filelist)

print('solution 3:遍历数组##############')
list=[2,3,4,5,6]
for index,j in  enumerate(list):
    print(index,j)

print('solution 4:按行遍历某文件##############')
filename='111.rtf'
with open(filename) as f:
    for index,j in  enumerate(f):
        print(index,j)

print('solution 5:map实现函数对list的遍历操作,python3返回的是迭代器##############')
a=map(lambda x:x+2,[1,2,3])
for i in a:
    print(i)
三、运行结果

/usr/local/bin/python3.6 /Users/guoxiya/Desktop/临时存储文件/test/11111.py
solution 1多层次遍历路径##############
root /Users/guoxiya/Desktop/临时存储文件/test
dirs ['1', '2', '.idea']
files ['.DS_Store', '111.rtf', '11111.py']
root /Users/guoxiya/Desktop/临时存储文件/test/1
dirs []
files []
root /Users/guoxiya/Desktop/临时存储文件/test/2
dirs ['3']
files ['112.rtf', '.DS_Store']
root /Users/guoxiya/Desktop/临时存储文件/test/2/3
dirs []
files ['.DS_Store', '113.rtf']
root /Users/guoxiya/Desktop/临时存储文件/test/.idea
dirs ['codeStyles', 'dictionaries']
files ['workspace.xml', 'modules.xml', 'misc.xml', 'test.iml']
root /Users/guoxiya/Desktop/临时存储文件/test/.idea/codeStyles
dirs []
files ['codeStyleConfig.xml']
root /Users/guoxiya/Desktop/临时存储文件/test/.idea/dictionaries
dirs []
files ['guoxiya.xml']
solution 2单层遍历某路径##############
['.DS_Store', '111.rtf', '1', '11111.py', '2', '.idea']
solution 3:遍历数组##############
0 2
1 3
2 4
3 5
4 6
solution 4:按行遍历某文件##############
0 qqq

1 ww w

2 ee ee

4 rr

solution 5:map实现函数对list的遍历操作,python3返回的是迭代器##############
3
4
5

Process finished with exit code 0
————————————————————————————

对多维数据的遍历ndenumerate,ndindex
Z = np.arange(4).reshape(2,2)
for index, value in np.ndenumerate(Z):
    print(index, value)
print('')
for index in np.ndindex(Z.shape):
    print(index, Z[index])

(0, 0) 0
(0, 1) 1
(1, 0) 2
(1, 1) 3

(0, 0) 0
(0, 1) 1
(1, 0) 2
(1, 1) 3

 

 

 

 

 

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/834059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号