如何从一个数组中选取多个元素
如何快速简洁地从一个数组中选取多个元素呢?像perl的(split)那样切片。 python好象只支持连续的切片. 本帖最后由 ssfjhh 于 2014-09-15 10:11 编辑In : a = list('abcdefghijklmn')
In : a
Out: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
In : def getitems(a, *key):
...: return type(a)(map(lambda i:a, key))
...:
In : getitems(a, 1, 2, 5)
Out: ['b', 'c', 'f'] 3楼的代码不能用于字符串,略作修改,使其能够用于字符串。In : a = list('abcdefghijklmn')
In : a
Out: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
In : def getitems(a, *key):
...: if isinstance(a, str):
...: res = ''.join(map(lambda i:a, key))
...: else:
...: res = type(a)(map(lambda i:a, key))
...: return res
...:
In : getitems(a, 1, 2, 5)
Out: ['b', 'c', 'f']
In : getitems('abcdefghijklmnopq', 2, 5, 7, 9)
Out: 'cfhj'
页:
[1]