Создать массив python нужной длины

How to create an array of numbers 1 to n in python

An array is a collection of items of the same type stored at contiguous memory locations. To access the elements, you only need to know the memory address of the first item of an array which is also known as the base address. You can access all other items or traverse in an array by simply adding an offset to this base address. Python lists can also be treated as arrays but the lists can store multiple data items of different datatypes. This article is about how to create an array of numbers 1 to N in Python. If you want to learn more about Python Programming, visit Python Programming Tutorials.

To create an array of numbers from 1 to N in python, range() Function can be used. Other methods include creation of an array using user-defined function, numpy.arrange() function and python array module. All these methods can be used for creating an array of numbers 1 to N in Python.

In the first three methods, we’ll see how lists can be treated as arrays. Python has a module called array which is used to work only with specific data values. The last method discusses how to create an array using this module. Let’s discuss all these methods in detail.

Читайте также:  Таблица кодов html php

Creating an array using the Range() Function

As discussed previously, python lists can be treated as arrays. To create an array of a certain range, we can use the range() function as it specifies the range of the list and then typecast the range() by using the list command as shown in the code below. We can set the range of the list from 1 to N and N should be any integer number.

#Creation of an array using Range() Function list = list(range(1,8)) print(list)

Creating an array by a user-Defined Function

Another way is to create a function and pass the length of an array as a parameter to this function. In the example below, we have created a function by the name of List-Function. The function takes parameter ‘n’ which represents the length of the array. In this function, a for loop is used which treats n as the last index of the array and appends the number in the List_array starting from 0 up to the maximum length ‘n’ as shown below.

def List_function(n): list_array = [] for i in range(n+1): list_array.append(i) return(list_array) print(List_function(10))

Creating an array using NumPy.ARRANGE() Function

The NumPy library provides an arrange() function which takes two parameters as integers and generates the numbers starting from the first parameter up to the last parameter. Typecast the arange() function using the list command and an array is created.

import numpy as np list_array = list(np.arange(1,13+1)) print(list_array)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

numpy.arange() is used to create an array of large sizes.

Читайте также:  Python flask отправить post запрос

Create an array using the Python Module Array

An array module of Python is used to create an array consisting of elements or items of same datatypes. The array module takes two arguments as input. The first one is the datatype of an array such as ‘i’ for integer. All other datatypes are given in this link. The second argument consists of the elements or items of an array.

def display(n,s): print ("The array created consists of following items: ", end =" ") for i in range (0, s): print (n[i], end =" ") print(" ") import array as arr # creating an array of integer datatype arr1 = arr.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) #print array display(arr1,len(arr1)) # creating an array of float datatype arr2 = arr.array('d', [0.5, 5.21, 3.14]) #print array display(arr2,len(arr2))
The array created consists of following items: 1 2 3 4 5 6 7 8 9 10 The array created consists of following items: 0.5 5.21 3.14 

In the example above, we have created two arrays arr1 and arr2 of integers and floating numbers. The function display here is used to print the contents of an array created. It takes two arguments: an array ‘n’ and the size of array ‘s’ created.

There are different operations that can be carried out on arrays such as insertion, deletion, sorting arrays into ascending and descending order, etc. Try them on your own. If you have any queries regarding this topic or any other topic related to Python programming language, let us know in the comments or contact us.

Источник

Массивы Python

Основы

В Питоне нет структуры данных, полностью соответствующей массиву. Однако, есть списки, которые являются их надмножеством, то есть это те же массивы, но с расширенным функционалом. Эти структуры удобнее в использовании, но цена такого удобства, как всегда, производительность и потребляемые ресурсы. И массив, и список – это упорядоченные коллекции, но разница между ними заключается в том, что классический массив должен содержать элементы только одного типа, а список Python может содержать любые элементы.

shapito_list = [1, 'qwerty', 4/3, [345, ['a', ]]] print(shapito_list) # Вывод: [1, 'qwerty', 1.3333333333333333, [345, ['a', ]]]

Создание массива

Существует несколько способ создать массив. Ниже приведены примеры как это можно сделать.

можно_так = [1, 2, 3, 4, 5] можно_так_2 = list('итерируемый объект') а_можно_и_так = [i for i in range(5)] print('можно_так:', можно_так) print('можно_так_2:', можно_так_2) print('а_можно_и_так:', а_можно_и_так) print('можно_так[0]:', можно_так[0]) print('а_можно_и_так[3]:', а_можно_и_так[3]) # Вывод: можно_так: [1, 2, 3, 4, 5] можно_так_2: ['и', 'т', 'е', 'р', 'и', 'р', 'у', 'е', 'м', 'ы', 'й', ' ', 'о', 'б', 'ъ', 'е', 'к', 'т'] а_можно_и_так: [0, 1, 2, 3, 4] можно_так[0]: 1 а_можно_и_так[3]: 3

Многомерный массив

Двухмерный массив в Python можно объявить следующим образом.

example_array = [[-1, 0, 0, 1], [2, 3, 5, 8]] print(example_array[0]) print(example_array[1]) print(example_array[0][3]) # Вывод: [-1, 0, 0, 1] [2, 3, 5, 8] 1
example_array = [[[-1, 0], [0, 1]], [[2, 3], [5, 8]]] print(example_array[0]) print(example_array[1]) print(example_array[0][1]) print(example_array[0][1][0]) # Вывод: [[-1, 0], [0, 1]] [[2, 3], [5, 8]] [0, 1] 0

Операции с массивами

Давайте теперь рассмотрим операции, которые Пайтон позволяет выполнять над массивами.

Обход массива с использованием цикла for

Мы можем использовать цикл for для обхода элементов массива.

example_array = [1, 2, 3] for i in range(len(example_array)): print(example_array[i]) # Вывод: 1 2 3

Здесь представлен подход, свойственный большинству языков программирования. В Python же есть свой, более удобный вариант.

example_array = [1, 2, 3] for i in example_array: print(i) # Вывод: 1 2 3

Обход многомерного массива

Для того чтоб получить элементы многомерного массива придётся использовать вложенные циклы.

example_array = [[1, 2], [3, 4]] for i in example_array: for x in i: print(x) # Вывод: 1 2 3 4

Добавление

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

example_array = [[1, 2], [3, 4]] example_array.insert(0, -1) example_array.insert(2, [-1, 13, 64]) print(example_array) # Вывод: [-1, [1, 2], [-1, 13, 64], [3, 4]]
example_array = [[1, 2], [3, 4]] example_array.append(-1) example_array.append([-1, 13, 64]) print(example_array) # Вывод: [[1, 2], [3, 4], -1, [-1, 13, 64]]
example_array = [1, 2, 3, 4] example_array.extend([5, 6]) print(example_array) # Вывод: [1, 2, 3, 4, 5, 6]

Определение размера

Используйте метод len() чтобы вернуть длину массива (число элементов массива).
Не стоит путать размер массива с его размерностью!

example_array = [[1, 2], [3, 4]] print('Размер массива:', len(example_array)) example_array.append(-1) print('Размер массива:', len(example_array)) example_array.append([-1, 13, 64]) print('Размер массива:', len(example_array)) # Вывод: Размер массива: 2 Размер массива: 3 Размер массива: 4

Поскольку индексация элементов начинается с нуля, длина массива всегда на единицу больше, чем индекс последнего элемента.

example_array = [[1, 2], [3, 4]] print('Равна ли длина массива номеру последнего элемента + 1?', len(example_array) is (example_array.index(example_array[-1]) + 1)) example_array.append(-1) print('Увеличили размер массива.') print('Равна ли теперь длина массива номеру последнего элемента + 1?', len(example_array) is (example_array.index(example_array[-1]) + 1)) # Вывод: Равна ли длина массива номеру последнего элемента + 1? True Увеличили размер массива. Равна ли теперь длина массива номеру последнего элемента + 1? True

Небольшое пояснение: метод списка .index() возвращает индекс элемента, значение которого совпадает с тем, которое передали методу. Здесь мы передаём значение последнего элемента и, таким образом, получаем индекс последнего элемента. Будьте осторожны: если в списке есть повторяющиеся значения, этот приём не сработает!

Срез

Срез Python предоставляет особый способ создания массива из другого массива.

example_array = [[1, 2], [3, 4]] print(example_array[::-1]) print(example_array[1:]) print(example_array[0][:-1]) # Вывод: [[3, 4], [1, 2]] [[3, 4]] [1]

Функция pop

В Python удалить ненужные элементы из массива можно при помощи метода pop, аргументом которого является индекс ячейки. Как и в случае с добавлением нового элемента, метод необходимо вызвать через ранее созданный объект.

example_array = [1, 2, 6, 3, 4] print(example_array.pop(4)) print(example_array) # Вывод: 4 [1, 2, 6, 3]

После выполнения данной операции содержимое массива сдвигается так, чтобы количество доступных ячеек памяти совпадало с текущим количеством элементов.

Методы массива

В Python есть набор встроенных методов, которые вы можете использовать при работе с list.

Метод Значение
append() Добавляет элементы в конец списка
clear() Удаляет все элементы в списке
copy() Возвращает копию списка
count() Возвращает число элементов с определенным значением
extend() Добавляет элементы списка в конец текущего списка
index() Возвращает индекс первого элемента с определенным значением
insert() Добавляет элемент в определенную позицию
pop() Удаляет элемент по индексу
remove() Убирает элементы по значению
reverse() Разворачивает порядок в списке
sort() Сортирует список

Модуль array

Если Вам всё-таки нужен именно классический массив, вы можете использовать встроенный модуль array. Он почти не отличается от структуры list, за исключением, пожалуй, объявления.
Вот небольшая демонстрация:

import array example_array = array.array('i', [1, 2, 6, 3, 4]) # превый аргумент указывает на тип элементов. i означает integer example_array.insert(0, -1) print('После вставки:', example_array) example_array.append(-1) print('После добавления в конец:', example_array) example_array.extend([5, 6]) print('После объединения со списком:', example_array) print('Удалён элемент:', example_array.pop(4)) print('После удаления элемента:', example_array) print('Срез:', example_array[0:4]) # Вывод: После вставки: array('i', [-1, 1, 2, 6, 3, 4]) После добавления в конец: array('i', [-1, 1, 2, 6, 3, 4, -1]) После объединения со списком: array('i', [-1, 1, 2, 6, 3, 4, -1, 5, 6]) Удалён элемент: 3 После удаления элемента: array('i', [-1, 1, 2, 6, 4, -1, 5, 6]) Срез: array('i', [-1, 1, 2, 6])

Типы элементов массива

Элементы массива в модуле array могут быть следующих типов:

Код типа Тип в C Тип в python
‘b’ signed char int
‘B’ unsigned char int
‘h’ signed short int
‘H’ unsigned short int
‘i’ signed int int
‘I’ unsigned int int
‘l’ signed long int
‘L’ unsigned long int
‘q’ signed long long int
‘Q’ unsigned long long int
‘f’ float float
‘d’ double float

Как Вы можете видеть, со строками модуль не работает.

Источник

Оцените статью