我们如何将负数扩展到 python 中双端队列的左侧?

How can we extend negative numbers to left side in a deque in python?

如果我在 python 3 中键入以下代码将负数扩展到双端队列的左侧

de=collections.deque([])
de.extendleft('-1-2-3-4-5-6')

我得到这样的输出

deque(['6', '-', '5', '-', '4', '-', '3', '-', '2', '-', '1', '-'])

相反,我想要这样的输出:

deque(['-6','-5''-4','-3','-2','-1'])

虽然丑陋但有效: 而不是

de.extendleft('-1-2-3-4-5-6')

使用

de.extendleft('-1-2-3-4-5-6'.replace('-',',-').split(',')[1:])

它有什么作用:

  • replace('-',',-') 添加了一个逗号,用于与 split 分隔。所以在这第一步中你得到:

    '-1-2-3-4-5-6'.replace('-',',-')=',-1,-2,-3,-4,-5,-6'
    
  • split(',')中你把之前加的逗号去掉,你可以把它拆分成一个列表:

    ',-1,-2,-3,-4,-5,-6'.split(',')=['', '-1', '-2', '-3', '-4', '-5', '-6']
    
  • 最后必须把0那个没用的space给退出,所以才把[1:]放在最后,所以最后的部分变成

    ['', '-1', '-2', '-3', '-4', '-5', '-6'][1:]=['-1', '-2', '-3', '-4', '-5', '-6']
    

所以最后列表变成了

['-1', '-2', '-3', '-4', '-5', '-6']

编辑:不要遵循这个答案,最好使用 space 而不是逗号作为分隔符。

它应该是一个列表而不是字符串。使用 '-1-2-3-4-5-6'.replace('-', ' -').split(' ')[1:]

import collections
de=collections.deque([])
de.extendleft([-1,-2,-3,-4,-5,-6])

import collections
de=collections.deque([])
de.extendleft('-1-2-3-4-5-6'.replace('-', ' -').split(' ')[1:])

您输入的是字符串。因此,它正在考虑 - 这也是一个元素。

from collections import deque

x = '-1-2-3-4-5-6'.replace('-', ' -').strip()
de = deque([])
de.extendleft(x.split())