在 Python 中将具有不同类型的项目列表作为字符串加入 [英] Join a list of items with different types as string in Python

查看:19
本文介绍了在 Python 中将具有不同类型的项目列表作为字符串加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加入一个项目列表.列表中的许多项是从函数返回的整数值;即,

I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,

myList.append(munfunc()) 

我应该如何将返回的结果转换为字符串以将其与列表连接?

How should I convert the returned result to a string in order to join it with the list?

我是否需要为每个整数值执行以下操作:

Do I need to do the following for every integer value:

myList.append(str(myfunc()))

是否有更 Pythonic 的方法来解决铸造问题?

Is there a more Pythonic way to solve casting problems?

推荐答案

调用 str(...) 是 Pythonic 将某些内容转换为字符串的方式.

Calling str(...) is the Pythonic way to convert something to a string.

您可能需要考虑为什么需要字符串列表.您可以将其保留为整数列表,并且仅在需要显示它们时才将整数转换为字符串.例如,如果您有一个整数列表,那么您可以在 for 循环中将它们一个一个地转换并用 , 连接它们:

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:

print(','.join(str(x) for x in list_of_ints))

这篇关于在 Python 中将具有不同类型的项目列表作为字符串加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆