以这种方式切片阵列 [英] Slicing Arrays in this way
问题描述
>> elegant_solution([1,2,3,4,5,6, 7,8,9,10])
>>elegant_solution([1,2,3,4,5,6,7,8,9,10])
[[1,2],[3,4],[5,6] ],[7,8],[9,10]]
-
通过 http://www.teranews.com
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
--
Posted via a free Usenet account from http://www.teranews.com
推荐答案
5月2日下午3:03,Tobiah< t ... @ tobiah.org写道:
On May 2, 3:03 pm, Tobiah <t...@tobiah.orgwrote:
>> elegant_solution([1,2,3,4,5,6,7,8,9,10])
>>elegant_solution([1,2,3,4,5,6,7,8,9,10])
[[1,2],[3,4],[5,6],[7,8],[9,10]]
-
通过免费的Usenet帐户发布来自http://www.teranews.com
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
--
Posted via a free Usenet account fromhttp://www.teranews.com
>> seq = range(1,11)
seq
>>seq = range(1,11)
seq
[1,2, 3,4,5,6,7,8,9,10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> > zip(seq [0 :: 2],seq [1 :: 2])
>>zip( seq[0::2],seq[1::2] )
[(1,2) ,(3,4),(5,6),(7,8),(9,10)]
如果你_really_需要列表然后...
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
if you _really_ need lists then...
>> map(list,zip(seq [0 :: 2],seq [1: :2]))
>>map(list, zip( seq[0::2],seq[1::2] ))
[[1,2],[3,4],[5,6],[7 ,8,[9,10]]
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
5月3日上午8:03,Tobiah< t ... @ tobiah.org写道:
On May 3, 8:03 am, Tobiah <t...@tobiah.orgwrote:
>> elegant_solution([1,2,3,4,5,6] ,7,8,9,10])
>>elegant_solution([1,2,3,4,5,6,7,8,9,10])
[[1,2],[3,4],[5,6],[7,8],[9,10]]
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
什么是你对优雅的定义吗?那么其他尺寸的
代码质量如何强大?和快?
您尝试了什么?
这里有一种可能性:
zip(source [:: 2],source [1 :: 2])
[我假设你不会因为获取元组而不是列表而感到不安]
What is your definition of "elegant"? What about other dimensions of
code quality like "robust" and "fast"?
What have you tried?
Here''s one possibility:
zip(source[::2], source[1::2])
[I''m presuming you won''t be upset by getting tuples instead of lists]
Matimus写道:
Matimus wrote:
5月2日下午3:03,Tobiah< t ... @ tobiah.orgwrote:
On May 2, 3:03 pm, Tobiah <t...@tobiah.orgwrote:
> >> elegant_solution([1,2,3,4,5,6,7,8,9,10])
> >>elegant_solution([1,2,3,4,5,6,7,8,9,10])
[[1,2],[3, 4],[5,6],[7,8],[9,10]]
-
通过免费的Usenet帐户发布来自http://www.teranews.com
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
--
Posted via a free Usenet account fromhttp://www.teranews.com
>>> seq = range(1,11)
seq
>>>seq = range(1,11)
seq
[1,2,3,4,5,6,7,8,9,10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(seq [0 :: 2],seq [1 :: 2])
>>>zip( seq[0::2],seq[1::2] )
[(1,2),(3,4),(5,6),(7,8),(9,10)]
如果你_really_需要列表然后...
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
if you _really_ need lists then...
>>> map(list,zip(seq [0 :: 2] ],seq [1 :: 2]))
>>>map(list, zip( seq[0::2],seq[1::2] ))
[[1,2],[3,4],[5,6], [7,8],[9,10]]
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
我想出了:
[[a [ x],a [x + 1]],x在范围内(0,10,2)]
我希望能有点简洁。
类似
list [:: 2:2]如果是这样的话已存在。
-
通过 http://www.teranews.com
I had come up with:
[[a[x], a[x + 1]] for x in range(0, 10, 2)]
I was hoping for something a little more concise.
Something like
list[::2:2] if that existed.
--
Posted via a free Usenet account from http://www.teranews.com
这篇关于以这种方式切片阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!