Informatics 9. Билингвальный учебник - [14]

Шрифт
Интервал

To access the items in a sublist, simply append an additional index:

>>> x[1]

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

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

# printing result

print(“List after sorting by 2nd element:”)

print(List)


Output

Original list:

[[‘Darkhan’, 4, 28], [‘Yerbol’, 2, 20], [‘Aibek’, 1, 20], [‘Askhat’, 3, 21]]

List after sorting by 2nd element:

[[‘Aibek’, 1, 20], [‘Yerbol’, 2, 20], [‘Askhat’, 3, 21], [‘Darkhan’, 4, 28]]


The lambda keyword lets us define a mini-function which receives List (in this case, our row) and returns the second element of List (List[1]).

Method #2 : Using sorted() + itemgetter()

This method can also be applied to perform this particular task. The advantage of this method is that it does not modify the original list. itemgetter() is used to get the index element by which the sort operation needs to be performed.


Example 2

# import itemgetter

from operator import itemgetter

# initializing list

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

# using sorted() + itemgetter to sort list

res = sorted(List, key = itemgetter(1))

# printing result

print(“List after sorting by 2nd element:”)

print(res)


Output

List after sorting by 2nd element:

[[‘Aibek’, 1, 20],

[‘Yerbol’, 2, 20],

[‘Askhat’, 3, 21],

[‘Darkhan’, 4, 28]]


Practice 1

1. Create and initialize two-dimensional list;

2. Every row should contain “Name” and “Year of birth”;

3. Sort list by Name;

4. Sort list by Year of birth.


Practice 2

1. Create a two-dimensional list;

2. Insert “Film names” and “Date of releases” to the list;

3. Sort list by Date of releases in ascending order and descending order.

Hint: use reverse.


Literacy

1. Is there any difference between sorting the normal list and multi-dimensional list?

2. What would be the result if we sort list by one element, then sort again by another element?


Terminology

specified – арнайы – указанный

circumstance – жағдай – обстоятельство

perform – орындау – выполнять

variation – вариация – вариация


3.9 INSERT/DELETE VALUES IN 2D LIST

You will:

learn to insert values in a two-dimensional list;

learn to update values in a two-dimensional list;

learn to delete values in a two-dimensional list.


Where two or three dimensional arrays can be used in real life?

Добавить элемент в двумерный список

Мы можем вставить новые элементы данных в определенную позицию, используя метод insert() и указав индекс.

В приведенном ниже примере новый элемент данных вставляется в позиции индекса 2.


Example 1

List = [[11, 12, 5, 2], [15, 6, 10], [10, 8, 12, 5],

List.insert(2, [0,5,11,13,6])

for x in List:

for y in x:

print(y, end = “ ”)

print()

Когда приведенный выше код выполняется, он дает следующий результат.