元組、列表、字典遍歷及相互轉(zhuǎn)換,從網(wǎng)上找到資料自己總結(jié)記錄一下,
轉(zhuǎn)載地址:https://blog.csdn.net/aYsd32/article/details/89766134
#coding:utf-8
"""" 元組遍歷 """""
""""直接遍歷元組值"""
tuple_all=("北京","上海","廣州","深圳")
for tuple1 in tuple_all:
print(tuple1)
""""通過索引遍歷"""
for tuple2 in range(len(tuple_all)):
print(tuple_all[tuple2])
#注意:元組是無法進(jìn)行重新賦值的,需要將元組進(jìn)行轉(zhuǎn)換后在進(jìn)行重新賦值
"""" 列表遍歷 """""
""""直接遍歷列表值"""
list_all=["北京","上海","廣州","深圳"]
for list1 in list_all:
print(list1)
""""通過索引遍歷"""
for list2 in range(len(list_all)):
print(list_all[list2])
"""" 字典遍歷 """""
""""利用key遍歷字典輸出value"""
dict_all={"城市1":"北京","城市2":"上海","城市3":"廣州","城市4":"深圳"}
for key1 in dict_all:
print(dict_all[key1])
""""遍歷字典的key值利用dict.keys()方法"""
for key2 in dict_all.keys():
print(key2)
""""遍歷字典的value值利用dict.values()方法"""
for value in dict_all.values():
print(value)
""""使用items遍歷字典的鍵值對(duì)"""
for k ,v in dict_all.items():
print({k:v})
""""元組轉(zhuǎn)化為列表"""
tuple_list=list(tuple_all)
print(tuple_list)
""""列表轉(zhuǎn)化為元組"""
list_tuple=tuple(list_all)
print(list_tuple)
""""元組轉(zhuǎn)化為字符串"""
tuple_str=str(tuple_all)
print(tuple_str,type(tuple_str))
""""列表轉(zhuǎn)化為字符串"""
list_str=str(list_all)
print(list_str,type(list_str))
""""字典key轉(zhuǎn)化為元組"""
key_tuple=tuple(dict_all)
print(key_tuple,type(key_tuple))
""""字典value轉(zhuǎn)化為元組"""
value_tuple=tuple(dict_all.values())
print(value_tuple,type(value_tuple))
""""字典key轉(zhuǎn)化為列表"""
key_list=list(dict_all)
print(key_list,type(key_list))
""""字典value轉(zhuǎn)化為列表"""
value_list=list(dict_all.values())
print(value_list,type(value_list))
""""字典轉(zhuǎn)化為字符串"""
dict_str=str(dict_all)
print(dict_str,type(dict_str))
""""字符串轉(zhuǎn)化為元組,要使用eval()函數(shù),否則會(huì)按每個(gè)字符進(jìn)行劃分生成元組"""
str_all="('北京', '上海', '廣州', '深圳')"
str_tuple=tuple(eval(str_all))
print(str_tuple,type(str_tuple))
""""字符串轉(zhuǎn)化為列表,同樣使用eval()函數(shù)"""
str_list=list(eval(str_all))
print(str_list,type(str_list))
""""字符串轉(zhuǎn)化為字典,同樣使用eval()函數(shù)"""
str="{'城市1': '北京', '城市2': '上海', '城市3': '廣州', '城市4': '深圳'}"
str_dict=eval(str)
print(str_dict,type(str_dict))