[英]How to join list with different types of elements in python?
list1 = [1,"3",2323,"pause"]
list2 = ["2","4","5"]
print ",".join(list1)
print ",".join(list2)
For the above code, the elements of list2
can be connected without any problems. 对于上面的代码,
list2
的元素可以没有任何问题地连接。 But the join of list1
reports error 但是
list1
的连接报告错误
TypeError: sequence item 0: expected string, int found
I know that join
works only for strings, then how to join the elements of a list with different types? 我知道
join
只适用于字符串,那么如何连接不同类型的列表元素?
Convert the items to strings first. 首先将项目转换为字符串。
",".join(str(elem) for elem in list1)
or 要么
",".join(map(str, list1))
Try it: 试试吧:
list1 = [1,"3",2323,"pause"]
list1 = [str(item) for item in list1]
print ",".join(list1)
str.join will work only on list of string. str.join仅适用于字符串列表。 So, apply str() to each element!
所以,将str()应用于每个元素! map() builtin function will come in handy.
map()内置函数会派上用场。
Try yourself, if you're gonna have problems - come back ;) 试试你自己,如果你有问题 - 回来吧;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.