Python中关于join函数的陷阱?

说明

最近在用Python的join函数连接多个列表时,出现了如下两个错误,即合并类型不一致。折腾了很久才找到原因,真是基础不牢,地动山摇。
TypeError: sequence item 3: expected str instance, int found

TypeError: can only concatenate list (not "str") to list

数据说明

a = ['a','c','c']
b = ['a','s','e']
c = [4,5,'e']
d = ['f']
e = 'g'
f = 'a'

正确示例

以下运行成功。

print('\t'.join(a+b))
print('\t'.join(a+d))
print('\t'.join(e+f))

# a       c       c       a       s       e
# a       c       c       f
# g       a

错误示例

join函数只能连接同类型的数据,要么都为list,要么都为str等。

同样列表内元素也是如此,必须是同类型的,否则需要转换。

print('\t'.join(a+c))
# TypeError: sequence item 3: expected str instance, int found
print('\t'.join(a+e))
# TypeError: can only concatenate list (not "str") to list

解决办法

格式转换

print('\t'.join(a+[str(i) for i in c]))
print('\t'.join(a+[e]))

# a       c       c       4       5       e
# a       c       c       g

Ref:https://my.oschina.net/u/4307735/blog/3647949

posted @ 2020-12-30 18:11  生物信息与育种  阅读(400)  评论(0编辑  收藏  举报