【问题标题】:Discontiguous array slices in PythonPython中的不连续数组切片
【发布时间】:2014-04-21 23:24:23
【问题描述】:

我想获得一个包含两个(或更多)不连续部分的数组切片。

例子:

>>> a=range(100)
>>> a[78:80; 85:97] # <= invalid syntax
[78, 79, 85, 86]

不接受该语法。最好的方法是什么?

更新: 上面的例子是在int 上,但我主要希望它适用于字符串。

例子:

>>> a="a b c d e f g".split()
>>> a[1:3; 4:6]
['b', 'c', 'e', 'f']

【问题讨论】:

    标签: python arrays slice


    【解决方案1】:

    怎么样

    >>> a = range(100)
    >>> a[78:80] + a[85:97]
    [78, 79, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96]
    

    更新:不确定您想要什么作为字符串示例的输出:

    >>> import string
    >>> a = list(string.lowercase[:7])
    >>> a[1:3] + a[4:6]
    ['b', 'c', 'e', 'f']
    

    【讨论】:

    • 谢谢,但我希望该解决方案也适用于字符串,例如,在 a="a b c d e f g".split() 上获得两部分切片。添加了对原始问题的更新以澄清。
    • @Frank:您希望输出的字符串示例是什么?
    • 查看更新的问题:&gt;&gt;&gt; a="a b c d e f g".split() &gt;&gt;&gt; a[1:3; 4:6] ['b', 'c', 'e', 'f']
    • sberry 解决方案仍然有效,只需添加两个列表
    【解决方案2】:

    一个 替代 sberry 的回答(虽然我个人认为他更好):也许你可以使用itemgetter

    from operator import itemgetter
    
    a="a b c d e f g".split()
    
    >>> print itemgetter(*range(1,3)+range(4,6))(a)
    ['b', 'c', 'e', 'f']
    

    from operator import itemgetter
    
    a="a b c d e f g".split()
    
    items = itemgetter(*range(1,3)+range(4,6))
    
    >>> print items(a)
    ['b', 'c', 'e', 'f']
    

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 2023-03-07
      • 2011-09-20
      • 2023-03-22
      • 1970-01-01
      • 2015-06-06
      • 2014-11-25
      • 2018-02-23
      相关资源
      最近更新 更多