list()函数
功能:转变为列表。
tup = ('a','b','c') dic = {'a1':1,'b2':2,'c3':3} string = "武汉加油" list1 = list(tup) list2 = list(dic.keys()) list3 = list(dic.items()) list4 = list(string) print(list1) print(list2) print(list3) print(list4) 输出: ['a', 'b', 'c'] ['a1', 'b2', 'c3'] [('a1', 1), ('b2', 2), ('c3', 3)] ['武', '汉', '加', '油']
'sep'.join(seq)函数
sep:一个字符分隔符 seq:要连接的字符串
功能:用指定分隔符连接字符串。
1 tup = ('a','b','c') 2 dic = {'a1':1,'b2':2,'c3':3} 3 string = "武汉加油" 4 ls = ['aa','bb','cc'] 5 6 a = '#'.join(tup) 7 b = '#'.join(dic) #输出的是键 8 b1 = '#'.join(dic.values()) #报错 9 b2 = '#'.join(dic.items()) #报错 10 c = '#'.join(string) 11 d = '#'.join(ls) 12 13 print(a) 14 print(b) 15 print(c) 16 print(d) 17 print(b1) #报错 18 print(b2) #报错 19 20 输出(除去报错项): 21 a#b#c 22 a1#b2#c3 23 武#汉#加#油 24 aa#bb#cc
其中行8报错原因:TypeError: sequence item 0: expected str instance, int found (TypeError:序列项0:预期的str实例,找到的int)
分析:dic中包含数字,join不能将其直接转化为字符。
dic1 = {'a1':'d','b2':'e','c3':'f'} b1 = '#'.join(dic1.values()) print(b1) 输出: d#e#f
行9报错原因:sequence item 0: expected str instance, tuple found (序列项0:预期的str实例,找到元组)
分析:序列中存在元组无法用join()连接
解放方案:先利用list函数把dic.items()里的元素转化为元组后,再使用for循环提取元组中的各个元素到另一列表。
dic1 = {'a1':'d','b2':'e','c3':'f'} list1 = list(dic1.items()) print(list1) list2 = [] for i in range(len(list1)): list2.append(list1[i][0]) list2.append(list1[i][1]) print(list2) b1 = '#'.join(list2) print(b1) 输出: [('a1', 'd'), ('b2', 'e'), ('c3', 'f')] ['a1', 'd', 'b2', 'e', 'c3', 'f'] a1#d#b2#e#c3#f