列表列表的切片行为问题
我得到一个这样的函数,
def f():
...
...
return [list1, list2]
它现在返回一个列表列表
[[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]]
当我执行以下操作时,
for i in range(0,2):print f()[i][0:10]
:它可以工作并打印切片列表
,但如果我
print f()[0:2][0:10]
这样做,它会打印列表,忽略 [0:10] 切片。
有什么方法可以使第二种形式起作用,还是我必须每次都循环才能获得所需的结果?
I got a function like
def f():
...
...
return [list1, list2]
this returns a list of lists
[[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]]
now when I do the following:
for i in range(0,2):print f()[i][0:10]
it works and print the lists sliced
but if i do
print f()[0:2][0:10]
then it prints the lists ignoring the [0:10] slicing.
Is there any way to make the second form work or do I have to loop every time to get the desired result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二个切片对从第一个切片返回的序列进行切片,所以是的,您必须以某种方式循环才能在其中进行切片:
The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within:
这两者的行为不同的原因是
f()[0:2][0:10]
的工作方式如下:f()
为您提供一个列表列表。[0:2]
为您提供一个列表,其中包含列表列表中的前两个元素。由于列表列表中的元素是列表,因此这也是列表列表。[0:10]
为您提供一个列表,其中包含步骤 2 中生成的列表列表中的前十个元素。换句话说,
f()[0:2][0 :10]
从一个列表列表开始,然后获取该列表列表的子列表(这也是一个列表列表),然后获取第二个列表列表的子列表(这也是一个列表)列表)。相反,
f()[i]
实际上从列表列表中提取第i
个元素,这只是一个简单列表(不是列表列表) 。然后,当您应用[0:10]
时,您是将其应用于从f()[i]
获得的简单列表,而不是列表列表。最重要的是,任何提供所需行为的解决方案都必须在某个时刻访问像
[i]
这样的单个数组元素,而不是只使用像[i:j] 这样的切片
。The reason why these two behave differently is because
f()[0:2][0:10]
works like this:f()
gives you a list of lists.[0:2]
gives you a list containing the first two elements in the list of lists. Since the elements in the list of lists are lists, this is also a list of lists.[0:10]
gives you a list containing the first ten elements in the list of lists that was produced in step 2.In other words,
f()[0:2][0:10]
starts with a list of lists, then takes a sublist of that list of lists (which is also a list of lists), and then takes a sublist of the second list of lists (which is also a list of lists).In contrast,
f()[i]
actually extracts thei
-th element out of your list of lists, which is just a simple list (not a list of lists). Then, when you apply[0:10]
, you are applying it to the simple list that you got fromf()[i]
and not to a list of lists.The bottom line is that any solution that gives the desired behavior will have to access a single array element like
[i]
at some point, rather than working only with slices like[i:j]
.一个 pythonic 循环是:
但根据你想要实现的目标,列表理解可能会更好。
或者您使用Python
map()
功能:不管怎样,没有办法不迭代列表并达到预期的结果。
A pythonic loop would be:
But depending on what you want to achieve, list comprehension might be even better.
Or you make use of Pythons
map()
function:One way or the other, there is no way to not iterate over the list and achieve the desired result.