元组、列表、字典遍历及相互转换,从网上找到资料自己总结记录一下,
转载地址: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])
#注意:元组是无法进行重新赋值的,需要将元组进行转换后在进行重新赋值
"""" 列表遍历 """""
""""直接遍历列表值"""
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遍历字典的键值对"""
for k ,v in dict_all.items():
print({k:v})
""""元组转化为列表"""
tuple_list=list(tuple_all)
print(tuple_list)
""""列表转化为元组"""
list_tuple=tuple(list_all)
print(list_tuple)
""""元组转化为字符串"""
tuple_str=str(tuple_all)
print(tuple_str,type(tuple_str))
""""列表转化为字符串"""
list_str=str(list_all)
print(list_str,type(list_str))
""""字典key转化为元组"""
key_tuple=tuple(dict_all)
print(key_tuple,type(key_tuple))
""""字典value转化为元组"""
value_tuple=tuple(dict_all.values())
print(value_tuple,type(value_tuple))
""""字典key转化为列表"""
key_list=list(dict_all)
print(key_list,type(key_list))
""""字典value转化为列表"""
value_list=list(dict_all.values())
print(value_list,type(value_list))
""""字典转化为字符串"""
dict_str=str(dict_all)
print(dict_str,type(dict_str))
""""字符串转化为元组,要使用eval()函数,否则会按每个字符进行划分生成元组"""
str_all="('北京', '上海', '广州', '深圳')"
str_tuple=tuple(eval(str_all))
print(str_tuple,type(str_tuple))
""""字符串转化为列表,同样使用eval()函数"""
str_list=list(eval(str_all))
print(str_list,type(str_list))
""""字符串转化为字典,同样使用eval()函数"""
str="{'城市1': '北京', '城市2': '上海', '城市3': '广州', '城市4': '深圳'}"
str_dict=eval(str)
print(str_dict,type(str_dict))