将 [ 作为起始字符和 ] 作为结束字符的字符串拆分为 Python 中的两个列表,用逗号分隔
Splitting string from [ as start character and ] as end character separated by comma into two lists in Python
我的输入是 [1,3,4],[1,2,6,8],我是使用正则表达式的新手。
我想将上面的输入分成两部分 1 3 4 和 1 2 6 8 并将它们视为单独的列表。
我试过跟随但它不起作用
pattern = re.compile(r'\[([^]]*)\]')
s=[1,3,4], [1,2,6,8]
print(pattern.findall(s))```
这是一个使用 re.findall
、字符串 split()
和列表理解的选项:
inp = "[1,3,4], [1,2,6,8]"
output = [x.split(',') for x in re.findall(r'\d+(?:,\d+)*', inp)]
print(output)
这会打印:
[['1', '3', '4'], ['1', '2', '6', '8']]
为什么需要使用正则表达式?您的输入已经被构造为列表元组:
list_a, list_b = eval("[1,3,4], [1,2,6,8]")
print(list_a)
[1, 3, 4]
print(list_b)
[1, 2, 6, 8]
我的输入是 [1,3,4],[1,2,6,8],我是使用正则表达式的新手。 我想将上面的输入分成两部分 1 3 4 和 1 2 6 8 并将它们视为单独的列表。 我试过跟随但它不起作用
pattern = re.compile(r'\[([^]]*)\]')
s=[1,3,4], [1,2,6,8]
print(pattern.findall(s))```
这是一个使用 re.findall
、字符串 split()
和列表理解的选项:
inp = "[1,3,4], [1,2,6,8]"
output = [x.split(',') for x in re.findall(r'\d+(?:,\d+)*', inp)]
print(output)
这会打印:
[['1', '3', '4'], ['1', '2', '6', '8']]
为什么需要使用正则表达式?您的输入已经被构造为列表元组:
list_a, list_b = eval("[1,3,4], [1,2,6,8]")
print(list_a)
[1, 3, 4]
print(list_b)
[1, 2, 6, 8]