如何拆分字符串以创建嵌套列表? [英] how do you split a string to create nested list?

查看:55
本文介绍了如何拆分字符串以创建嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何分割像这样的字符串

How would you split a string like

'1,55,6,89,2|7,29,44,5,8|767,822,999'

在两个定界符',''|'上的

,这样您将获得一个列表,其值如下:

on the two delimiters ',' and '|' such that you have a list with the values like:

[[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]

推荐答案

列表理解是最简单的方法.

List comprehension are the most terse way to accomplish this.

>>> s = '1,55,6,89,2|7,29,44,5,8|767,822,999'
>>> [[int(x) for x in ss.split(',')] for ss in s.split('|')]
[[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]

这篇关于如何拆分字符串以创建嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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