开发者

Shortest way to do this Python 3 list operation in PHP, JavaScript?

I am learning Python and I just read in a book that Python 3 lets you do this cool list operation开发者_如何学编程:

first, *middle, last = [1, 2, 3, 4, 5]

first: 1 middle: [2, 3, 4] last: 5

This is great if I want to iterate through the middle of the list, and do separate things with the first and last items.

What's the easiest (read: most sugary) way to do this in Python 2.x, PHP, and JavaScript?


python 2.x

first, middle, last = a[0], a[1:-1], a[-1]


A solution in PHP could be the following, using array_shift and array_pop:

$first = array_shift($arr);
$last = array_pop($arr);
$middle = $arr;


On Python2, you can just use slice notation, also it's easier to read I think.

>>> t = (1, 2, 3, 4, 5)
>>> a, b, c = t[0], t[1:-1], t[-1]
>>> a, b, c
(1, (2, 3, 4), 5)


In PHP:

list($first, $middle, $last) = array($array[0], array_splice($array, 1, -1), $array[1]);

It destroys the original array though, leaving only the first and last elements.


Python 2:

first, middle, last = a[0], a[1:-1], a[-1]

PHP:

$first = array_shift($arr);
$last = array_pop($arr);
$middle = $arr;

JavaScript:

var a = Array.apply(0,myAry), first = a.shift(), last = a.pop(), middle = a;

For the JavaScript sample, I created a copy of the array so as not to destroy the original.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜