列表的切片行为问题 [英] slicing behaviour question of a list of lists

查看:42
本文介绍了列表的切片行为问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的功能

def f():
    ...
    ...
    return [list1, list2]

这将返回列表列表

[[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

但如果我这样做

print f()[0:2][0:10]

然后打印列表,忽略[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?

推荐答案

这两个行为不同的原因是因为 f()[0:2] [0:10] 的工作方式如下:

The reason why these two behave differently is because f()[0:2][0:10] works like this:

  1. f()为您提供列表列表.
  2. [0:2] 为您提供一个列表,其中包含列表列表中的前两个元素.由于列表列表中的元素是列表,因此也是列表列表.
  3. [0:10] 为您提供了一个列表,其中包含在步骤2中生成的列表的前十个元素.
  1. f() gives you a list of lists.
  2. [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.
  3. [0:10] gives you a list containing the first ten elements in the list of lists that was produced in step 2.

换句话说, f()[0:2] [0:10] 从列表列表开始,然后获取该列表列表的子列表(这也是列表的列表).列表),然后获取列表的第二个列表的子列表(也是列表的列表).

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).

相反, f()[i] 实际上从列表列表中提取第 i 个元素,这只是一个简单列表(不是列表)列表).然后,当您应用 [0:10] 时,会将其应用到从 f()[i] 获得的简单列表中,而不是列表中的列表中

In contrast, f()[i] actually extracts the i-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 from f()[i] and not to a list of lists.

最重要的是,任何提供所需行为的解决方案都必须在某个时候访问像 [i] 这样的单个数组元素,而不是仅使用像 [i:j] .

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].

这篇关于列表的切片行为问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆