Python中的不连续数组切片
我想得到一个有两个(或更多)不连续部分的数组切片 例如:Python中的不连续数组切片,python,arrays,slice,Python,Arrays,Slice,我想得到一个有两个(或更多)不连续部分的数组切片 例如: >>> a=range(100) >>> a[78:80; 85:97] # <= invalid syntax [78, 79, 85, 86] >>> a="a b c d e f g".split() >>> a[1:3; 4:6] ['b', 'c', 'e', 'f'] 那怎么办 >>> a = range(100) >&g
>>> a=range(100)
>>> a[78:80; 85:97] # <= invalid syntax
[78, 79, 85, 86]
>>> a="a b c d e f g".split()
>>> a[1:3; 4:6]
['b', 'c', 'e', 'f']
那怎么办
>>> 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']
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']
或
谢谢,但我希望解决方案也适用于字符串,例如,在
a=“a b c d e f g”.split()
上获得两部分的切片。对原始问题添加了更新以澄清。@Frank:您希望字符串示例的输出是什么?请参阅更新后的问题:>>a=“a b c d e f g”.split()>>>a[1:3;4:6]['b','c','e','f']
sberry解决方案仍然有效,只需添加两个列表即可
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']