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



# 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: