1 tup = ([‘a‘,‘a1‘],[‘b‘,‘b2‘],[‘c‘,‘c3‘]) 2 ls = [[‘d‘,1,],[‘e‘,2],[‘f‘,3]] 3 b = [] 4 5 #for i in range(2): 6 # a = ls[0][i] + ":" + ls[1][i] + ":" + ls[2][i] #该条指令会报错 7 # b.append(a) 8 for i in range(2): 9 a = tup[0][i] + ":" + tup[1][i] + ":" + tup[2][i] 10 b.append(a) 11 12 print(b) 13 14 输出 > [‘a:b:c‘, ‘a1:b2:c3‘]
该指令会报错的原因:can only concatenate str (not "int") to str => 只能将str(而不是“ int”)连接到str
分析:这是由于对a进行赋值时,只能将字符串连接而不能连接整型int。
解决方案:
1 ls = [[‘d‘,1,],[‘e‘,2],[‘f‘,3]] 2 b = [] 3 4 for i in range(2): 5 b[i] = "{}:{}:{}".format(ls[0][i],ls[1][i],ls[2][i]) 6 7 print(b) 8 9 输出 > [‘d:e:f‘, ‘1:2:3‘]
Python学习笔记——列表需要同时连接整型和字符串时的解决方案
原文:https://www.cnblogs.com/zhengmq2010/p/12267762.html