Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拆分'-2-1';进入-2和-1_Python_Python 3.x_Split - Fatal编程技术网

Python 拆分'-2-1';进入-2和-1

Python 拆分'-2-1';进入-2和-1,python,python-3.x,split,Python,Python 3.x,Split,我有一个字符串,看起来像'-2--1',对于我的问题,它的意思是从-2到-1。我想从字符串中访问这两个数字。str.split(“-”)在这种情况下不起作用。我有什么选择 编辑:我也可以有一个像“2-5”这样的字符串,意思是从2到5(在本例中,我需要提取2和5),或者像“-2-5”这样的字符串,意思是-2到5(-2和5是本例中的重要数字)。如果总是有一个双破折号--你可以这样做 s = '-2--1' s.replace('--',' -').split(' ') # ['-2', '-1']

我有一个字符串,看起来像'-2--1',对于我的问题,它的意思是从-2到-1。我想从字符串中访问这两个数字。str.split(“-”)在这种情况下不起作用。我有什么选择


编辑:我也可以有一个像“2-5”这样的字符串,意思是从2到5(在本例中,我需要提取2和5),或者像“-2-5”这样的字符串,意思是-2到5(-2和5是本例中的重要数字)。

如果总是有一个双破折号
--
你可以这样做

s = '-2--1'
s.replace('--',' -').split(' ') # ['-2', '-1']

您可以使用正则表达式查找所有数字

>>> import re 
>>> re.findall(r'-?\d+', '-2--1')
['-2', '-1']
这将适用于数字之间的任何字符。e、 g

>>> re.findall(r'-?\d+', '-2---$&234---1')
['-2', '234', '-1']

但是它假设一个数字前面有一个
-
,这个数字会变成负数,当然,在数字后面的连字符上有一个拆分:

import re
s = '-1--2'
result = [int(d) for d in re.findall(r'-?\d+', s)]
def splitrange(s):
    return re.split(r'(?<=\d)-', s)
拆分数字:

split= str.split('-')
用于应用否定的函数:

def actual(ns, minus=False):
    if not ns:
        return
    n, *rest = ns
    if n == '':
        yield from actual(rest, not minus)
        return
    yield -int(n) if minus else int(n)
    yield from actual(rest)
现在你可以实现:

numbers = list(actual(split))
它还将处理多个否定

numbers = list(actual(split))