用Python遍历字符串、列表、元祖、字典、集合

#字符串遍历
str='aaabbbbccc'
for i in str:
    print(i)
#列表遍历
l=['1','a','b']
#方法1 遍历值
for i in l:
    print(i)
#方法2 索引位置和对应值都遍历出来,此方法还可以应用在元祖与字符串上
for k,v in enumerate(l):
    print(k,v)
#元祖遍历
t=(1,'aa','哈')
for i in t:
    print(i)
#字典遍历
d={1:'a',2:'b',3:'c'}
#方法1
for i in d:
    print(i,d[i])
#方法2
for k,v in d.items():
    print(k,v)

#集合遍历
se={'a','b',1,2}
for i in se:
    print(i)

反向遍历reversed()

t=(1,'aa','哈')
for i in reversed(t):
    print(i)

同时遍历两个或更多的序列zip()

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))

延伸学习zip()打包

a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)     # 打包为元组的列表
#结果:[(1, 4), (2, 5), (3, 6)]
zip(a,c)# # 元素个数与最短的列表一致
#结果:[(1, 4), (2, 5), (3, 6)]

遍历列表中的列表元素–利用函数进行递归,循环读取

#如何遍历列表中的列表
def l(a):
    for i in a:
        if isinstance(i,(str,int)):
            print(i)
        else:
            l(i)#直接利用函数来递归循环
if __name__=='__main__':
    a = [[1, [1, 2]], 'cc', 3, ['a', 'b'],('哈哈哈','hhh')]
    l(a)

结果

1
1
2
cc
3
a
b
哈哈哈
hhh
#递归遍历字典

def list_dictionary(d, n_tab=-1):
    if isinstance(d, list):
        for i in d:
            list_dictionary(i, n_tab)
    elif isinstance(d, dict):
        n_tab+=1
        for key, value in d.items():
            print("{}key:{}".format("\t"*n_tab, key))
            list_dictionary(value, n_tab)
    else:
        print("{}{}".format("\t"*n_tab, d))

if __name__=='__main__':
    a = [[1, [1, 2]], 'cc', 3, ['a', 'b'],('哈哈哈','hhh'),{99:'goos'}]
    list_dictionary(a)

    b={'dd':'3333','age':{1:'a',2:'b'},'old':{3:"c",4:'d'},'cl':{5:'gg',8:"哈哈"}}
    list_dictionary(b)

快速将列表的内容转为字符串

a=["aa","ddd"]
print(",".join(a))

列表元素操作–每个元素都加一个字符

方法一:

 a='a'
 b=['a','b']
 c=list(map(lambda x: x+a,b))# 使用 lambda 匿名函数
 print(c)

方法二

c=['a'+x for x in b]#列表前面加某一个字符
print(c)

结果:[‘aa’, ‘ab’]

列表元素怎么从int改成str

a=[1,2]
c=[str(i) for i in a ]
print(c)

结果
[‘1’, ‘2’]

你可能感兴趣的:(Python,python,开发语言)