在对象数组而不是字符串数组上的Python string.join(list)

编程入门 行业动态 更新时间:2024-10-27 07:25:57
本文介绍了在对象数组而不是字符串数组上的Python string.join(list)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Python中,我可以这样做:

In Python, I can do:

>>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c'

有对象列表时,有什么简单的方法可以做到这一点?

Is there any easy way to do the same when I have a list of objects?

>>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, instance found

还是我必须求助于for循环?

Or do I have to resort to a for loop?

推荐答案

您可以改用列表推导或生成器表达式:

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression

更多推荐

在对象数组而不是字符串数组上的Python string.join(list)

本文发布于:2023-11-04 12:33:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   而不是   对象   join

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!