Question on the list section of a list of lists

I got a function like

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

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 prints lists of chopped

but if i do

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

then it prints lists that ignore the slice [0:10].

Is there a way to make the second form work, or do I need to cyclically get the desired result every time?

+3
source share
3 answers

The reason these two behave differently is because it f()[0:2][0:10]works as follows:

  • f() provides a list of lists.
  • [0:2]provides a list containing the first two items in a list of lists. Since the items in a list of lists are lists, it is also a list of lists.
  • [0:10] , , 2.

, f()[0:2][0:10] , ( ), ( ).

, f()[i] i - , ( ). , [0:10], , f()[i], .

, , , - , [i], , [i:j].

+7

, , , - , :

[x[0:10] for x in f()[0:2]]
+10

:

for list in f()[0:2]:
    print list[0:10]

, , .

Pythons map():

def print_sub(x):
    print x[0:10]

map(print_sub, f()[0:2])

, .

0

Source: https://habr.com/ru/post/1737449/


All Articles