塞图宝 发表于 2014-09-15 06:05

如何从一个数组中选取多个元素

如何快速简洁地从一个数组中选取多个元素呢?像perl的(split)那样切片。

q1208c 发表于 2014-09-15 07:37

python好象只支持连续的切片.

ssfjhh 发表于 2014-09-15 10:09

本帖最后由 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']

ssfjhh 发表于 2014-09-15 12:41

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]
查看完整版本: 如何从一个数组中选取多个元素