Встроенные функции python: какие нужно знать и на какие не стоит тратить время

Списки из неизменяемых объектов

Можем ли мы сделать список кортежей? Tuple является неизменяемым объектом, а список — изменяемым. Итак, если мы объявим список кортежей, станут ли они изменяемыми? Давайте проверим это.

>>> list1.insert(6,("element1","element2"))
>>> list1

>>> type(list1)
<type 'list'>
>>> type(list1)
<type 'tuple'>
>>> list1=3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Таким образом, даже если неизменяемый объект хранится в списке, Python не изменяет его свойства.

Список может иметь любой тип данных в качестве элемента, будь то словарь, кортеж, строка или другой список. Это одна из причин, почему список так часто используется программистами.

О списках следует знать куда больше, чем описано в этой статье. Со многими особенностями и свойствами вы познакомитесь, когда начнете работать со списками. Но чтобы научиться продвинутому использованию, всегда необходимо фундаментальное понимание. В этой статье мы рассмотрели самые основы. Если вы поняли эти операции, вы готовы к дальнейшему изучению и базовому использованию списков.

Итак, базовое понимание есть — можно двигаться дальше уже самостоятельно. Для закрепления мы бы рекомендовали самостоятельно поиграться со списками в консоли, попробовать их в сочетании с другими типами данных, циклами, функциями. А мы желаем вам удачи в дальнейшем изучении языка Python.

Проходите тест по Python и поймите, готовы ли вы идти на курсы

The syntax for PythonString Count()

Python count function syntax:

string.count(char or substring, start, end)

Parameters of Python Syntax

  • Char or substring: You can specify a single character or substring you are wants to search in the given string. It will return you the count of the character or substring in the given string.
  • start : (optional) It indicates the start index from where the search will begin. If not given, it will start from 0. For example, you want to search for a character from the middle of the string. You can give the start value to your count function.
  • end: (optional) It indicates the end index where the search ends. If not given, it will search till the end of the list or string given. For example, you don’t want to scan the entire string and limit the search till a specific point you can give the value to end in your count function, and the count will take care of searching till that point.

ReturnValue

The count() method will return an integer value, i.e., the count of the given element from the given string. It returns a 0 if the value is not found in the given string.

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example −

#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined

Access Items

You access the list items by referring to the index number:

Example

Print the second item of the list:

thislist =
print(thislist)

Example

Print the last item of the list:

thislist =
print(thislist)

Range of Indexes

You can specify a range of indexes by specifying where to start and where to
end the range.

When specifying a range, the return value will be a new list with the
specified items.

Example

Return the third, fourth, and fifth item:

thislist =
print(thislist)

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to «orange»:

thislist =
print(thislist)

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from «cherry» and to the end:

thislist =
print(thislist)

Example

This example returns the items from index -4 (included) to index -1 (excluded)

thislist =
print(thislist)

Python NumPy

NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution

NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations

Разделение строки с использованием разделителя

Python может разбивать строки по любому разделителю, указанному в качестве параметра метода . Таким разделителем может быть, например, запятая, точка или любой другой символ (или даже несколько символов).

Давайте рассмотрим пример, где в
качестве разделителя выступает запятая
и точка с запятой (это можно использовать
для работы с CSV-файлами).

print("Python2, Python3, Python, Numpy".split(','))
print("Python2; Python3; Python; Numpy".split(';'))

Результат:

Как видите, в результирующих списках
отсутствуют сами разделители.

Если вам нужно получить список, в
который войдут и разделители (в качестве
отдельных элементов), можно разбить
строку по шаблону, с использованием
регулярных выражений (см. ). Когда вы берете шаблон в
захватывающие круглые скобки, группа
в шаблоне также возвращается как часть
результирующего списка.

import re

sep = re.split(',', 'Python2, Python3, Python, Numpy')
print(sep)
sep = re.split('(,)', 'Python2, Python3, Python, Numpy')
print(sep)

Результат:

Если вы хотите, чтобы разделитель был частью каждой подстроки в списке, можно обойтись без регулярных выражений и использовать list comprehensions:

text = 'Python2, Python3, Python, Numpy'
sep = ','

result = 
print(result)

Результат:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector