python-数据装换

list

list to tuple

li = ['test1', 'test2', 'test3', 123]
# tuple
print(tuple(li))  # ('test1', 'test2', 'test3', 123)

list to str

li = ['test1', 'test2', 'test3']
# str
print(str(li), type(str(li)))  # ['test1', 'test2', 'test3'] <class 'str'>
# join 列表中不能有数字
print(" ".join(li), type(" ".join(li)))  # test1 test2 test3 <class 'str'>

tuple

tuple to list

tuple1 = ("test1", "test2", "test3")
tuple2 = (1, 2, 3)
# list
list_tuple = list(tuple1)
print(list_tuple)  # ['test1', 'test2', 'test3']
print(list(tuple2))  # [1, 2, 3]

tuple to str

tuple1 = ("test1", "test2", "test3")
# str
str_ = str(tuple1)
print(str_, type(str_))  # ('test1', 'test2', 'test3') <class 'str'>
# join
print(" ".join(tuple1))  # test1 test2 test3


tuple2 = ("test1", "test2", "test3", 2)
# 在运用join方法时,元组里面的元素必须的字符串
# print(" ".join(tuple2))  # TypeError: sequence item 3: expected str instance, int found
 
# 数字组成的元组也是不能使用join,必须是字符串
tuple3 = (1, 2, 3)
# print(" ".join(tuple3))  # TypeError: sequence item 0: expected str instance, int found

dict

dict to list

dic = {"name": "Yang", "age": 123}
print(list(dic)) # ['name', 'age']  返回键

dict to tuple

dic = {"name": "Yang", "age": 123}
print(tuple(dic)) # ('name', 'age')  返回键

dict to str

dic = {"name": "Yang", "age": 123}
print(str(dic))  # {'name': 'Yang', 'age': 123}
print(' '.join(dic))  # name age

str

str to list

s = "test"
print(list(s))  #  ['t', 'e', 's', 't']
s2 = "123abc"
print(list(s2))  #  ['1', '2', '3', 'a', 'b', 'c']

str to tuple

s = "test"
print(tuple(s))  # ('t', 'e', 's', 't')
s2 = "123abc"
print(tuple(s2))  # ('1', '2', '3', 'a', 'b', 'c')

str to dict

str2 = "{'key1':'valu1','key2':'valu2'}"
dict2 = eval(str2)
print(dict2, type(dict2))  # {'key1': 'valu1', 'key2': 'valu2'} <class 'dict'>


常见的坑

l1 = [11, 22, 33, 44, 55]
将此列表索引为奇数位对应的元素全部删除.

l1 = [11, 22, 33, 44, 55]
# 将此列表索引为奇数位对应的元素全部删除.

# 方法一:
# del l1[1::2]
# print(l1)

# 方法二:错误示例:坑

# 循环一个列表时,不要改变列表的大小.这样会影响你最后的结果.
# for index in range(len(l1)):
#     if index % 2 == 1:
#         # index 奇数
#         l1.pop(index)
# print(l1)

# 方法三
# new_l = []
# for index in range(len(l1)):
#     if index % 2 == 0:
#         new_l.append(l1[index])
# # print(new_l)
# l1 = new_l
# print(l1)

# 方法三:
# for index in range(len(l1)-1,-1,-1):
#     if index % 2 == 1:
#         l1.pop(index)
# print(l1)

dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'name': 'alex'}
将字典中的key中含有k元素的所有键值对删除.

# 错误代码
'''坑
dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'name': 'Tom'}
for key in dic:
    if 'k' in key:
        dic.pop(key)
print(dic)  # untimeError: dictionary changed size during iteration
'''
# 循环一个字典时,不能改变字典的大小,这样会报错.

l1 = []  # 存放满足条件的key
for key in dic:
    if 'k' in key:
        l1.append(key)
# print(l1)
for key in l1:  # 在遍历key进行删除
    dic.pop(key) # 或 del dic[key]
print(dic)
posted @ 2019-08-04 20:37  yangchangjie  阅读(156)  评论(0编辑  收藏  举报