python - 如何将单个元素加入到 Python 中的字符串列表中

标签 python string list join

我有一个列表列表,例如y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]] 我想将每个内部列表转换为由“/”分隔的字符串,并输出各个字符串的列表。我怎样才能在Python中做到这一点?

最佳答案

您可以使用str.join之后mapping list comprehension 中的整数到字符串:

>>> y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
>>> formatted_y = ['/'.join(map(str, inner_list)) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

或者,如果您愿意,可以使用几个嵌套列表推导式:

>>> formatted_y = ['/'.join(str(x) for x in inner_list) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

要返回原始版本,您可以使用 str.split在列表压缩内:

>>> original_y = [list(map(int, inner_str.split('/'))) for inner_str in formatted_y]
>>> original_y
[[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]

关于python - 如何将单个元素加入到 Python 中的字符串列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150267/

相关文章:

python - Keras - CNN 输入形状不兼容

c++ - 将 std::string 复制到 char*(对于 TCP/IP 套接字)

python - 创建表并从字典中的列表中排序数据

Python:根据数字序列分割DataFrame

python - 如何编写注册账户测试用例?

python - 如果有两个以上唯一值,则过滤 df - pandas

python - 正则表达式 : How do I find a sub-string that is between two regular expression matches?

ios - 在 Swift 中使用带有 "İ"字符的 lowercaseString

python - 如何将这些元素附加到 python 中的数组?

python - python 对象列表,每个对象都有自己的数组字典。附加到一个附加到所有