Informatics 9. Билингвальный учебник | страница 28



>>> x[1][0]

‘bb’

>>> x[1][1]

[‘ccc’, ‘ddd’]

All the usual syntax regarding indices and slicing applies to sublists as well:

>>> x[1][1][-1]

‘ddd’

>>> x[1][1:3]

[[‘ccc’, ‘ddd’], ‘ee’]

>>> x[3][::-1]

[‘ii’, ‘hh’]


Practice 1

Write correct index to print out “big red apple“.

fruits = [[“banana”, “cherry”, “apple”], [“green”, “orange”, “red”,],

[“small”, “medium”, “big”]]


Creating nested lists

Suppose that two numbers are given: the number of rows of n and the number of columns m.

You must create a list of size nЧm, filled with zeros.

A possible way: you can create a list of n elements (say, of n zeros) and then make each of the elements a link to another one-dimensional list of m elements:

n = 3

m = 4

a = [0] * n

for i in range(n):

a[i] = [0] * m

Another way: create an empty list and then append a new element to it n times (this element should be a list of length m):

n = 3

m = 4

a = [0] * n

for i in range(n):

a[i] = [0] * m

But the easiest way is to use the generator, creating a list of n elements, each of which is a list of m zeros:

n = 3

m = 4

a = [[0] * m for i in range(n)]

In this case, each element is created independently from the others. The list [0] * m is n times constructed as the new one, and no copying of references occurs.


Practice 2

Create 5x5 list and change item at index[3][2].


Literacy

1. What is the difference between normal list and nested list?

2. Where we can use two-dimensional array?

Give three real-life examples.


Terminology

Nested – кірістірілген – вложенный

two-dimensional – екі өлшемді – двумерный

arbitrary – ерікті, еркін – произвольный

regarding – қатысты – относительно


3.8 SORTING TWO-DIMENSIONAL LIST

You will:

learn to sort two- dimensional arrays.


Сортировать по определенному индексу

Мы можем отсортировать список, используя обычную функцию сортировки. Это сортирует список по первому индексу списков. Но чаще всего могут возникать обстоятельства, которые требуют сортировки списка по другим элементам индекса, чем первый. Давайте обсудим некоторые способы выполнения этой задачи.


Method #1 : Using sort() + lambda

sort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index.


Example 1

# initializing list

List = [[“Darkhan”, 4, 28], [“Yerbol”, 2, 20], [“Aibek”, 1, 20], [“Askhat”, 3, 21]]

# printing original list

print(“Original list:”)

print(List)

# using sort() + lambda to sort list

List.sort(key = lambda List: List[1])