Рубрики
Без рубрики

Наиболее полезные последовательности в Python для начинающих 👨‍💻

Сегодня в этом блоге мы узнаем о самых полезных последовательностях, которые должен каждый программист Python … С тегом Python, Tutorial, Beginters, Codenewbie.

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

Вот повестка дня.

Повестка дня

  • Что такое последовательность?
  • Наиболее полезные последовательности
  • Что такое список?
  • Что такое понимание списка?
  • Как создать и принять ввод в список?
  • Функция, предоставленная классом списка
  • Что такое Str?
  • Как создать и принять вклад в STR?
  • Функция, предоставленная классом STR
  • Что такое кортеж?
  • Разница между кортежей и списком?
  • Как создать и принять вклад в кортеж?
  • Функция, предоставленная классом Tuple
  • Методы встроения для любых последовательностей
  • Вывод

Что такое последовательность?

  • Последовательности – это универсальный термин для Заказано набор Что означает, что порядок, в котором мы вход Элементы будут такими же, когда мы доступ их.
 Input: [1,2,3,4,5]

Так что здесь, если я пересекаю с помощью цикла, он печатает выход в том же порядке, что и вводные данные.

  • Последовательности итерационные, но итерабильные не может быть последовательности как установлен и диктат
  • Последовательность имеет концепцию индексации.

Наиболее полезная последовательность

Есть 3 наиболее полезных последовательностей.

  • стр
  • список
  • кортеж

Список – самая полезная последовательность Мы обсудим их один за другим. Итак, давайте начнем с список

Что такое список?

  • Список – это последовательность
  • Список хранит множество элементов в одной переменной
list=[1,'UG-SEP','dev',1.2,(7,'Python')]
  • Список может содержать гетерогенный элемент.
  • Список изменен.

Что такое понимание списка?

Понимание списка предлагает синтаксис для сжатия кода, который он использовал для ввода в список только одной строкой. Это очень удивительная функция для сжатия кода и простой для понимания.

Синтаксис

List= [ expression(element) for element in old List if condition ]

Мы узнаем, как получить ввод от пользователя, используя Понимание списка В форвардной теме

Как создать и присвоить значение в списке?

Список создается с использованием квадратных кронштейнов ([]) в квадратных скобках мы пишем элементы, разделяющие запятые (,)

list=['Welcome','Dev','Community']

Как вы можете видеть, я пишет элементы, разделяющие запятые.

Как создать пустой список?

# if the square brackets are empty it will considered as empty list
l1=[]
# list() function used to creates list objects
l2=list()

Как взять вклад от пользователя

# Using List comprehension
l1=[eval(i) for i in input("Enter data separating by commas").split(',')]

# So in the above line what happen is that first we will enter in
# list comprehension and take input from user after that it will 
# be split each element using commas as the criteria the split() 
# function split() string on a given criteria and I pass , as the 
# criteria so no the each element separated by , are treated as 
# list element and now the for run and we evaluate the element and 
# assign it.

# using for loop
# create a empty list
l2=list()
# take the size of list
for i in range(0,int(input("Enter the size"))):
# append is a function to add data at the last of the list we will 
# learn about it 
     l2.append(eval(input()))

Функция, предоставленная классом списка

 append() : used to append element at the end of the list
 clear()  : to remove all element from the list
 copy()   : return shallow copy of the list
 count()  : to the number of occurrence of a particular element
 index()  : to get the index of a particular element
 insert() : to insert element at a particular index
 pop()    : to pop a particular element by index no. remove the 
             last element if index not provided
 sort()   : to sort the element in an order
 reverse(): to reverse the list
 remove() : remove the particular element

Синтаксис:

l=[1,2,3]
# append 4 at the end so l=[1,2,3,4]
l.append(4)
# clear all element l=[]
l.clear()
# shallow copy of l shlcpy=[]
shlcpy=l.copy()
# count the occurrence of 1 but before that let add some value in l
l=[1,2,2,3,1,3,5,7]
print(l.count(1))
# index of a particular element prints the first occurrent index 0
print(l.index(1))
# insert at the 2 and 4th index l=[1,2,2,3,2,1,3,5,7]
l.insert(4,2)
# pop 0 index value l=[2,2,3,2,1,3,5,7]
l.pop(0)
# sort the list l=[1,2,2,2,3,3,5,7]
l.sort()
# reverse the list l=[7,5,3,3,2,2,2,1]
l.reverse()
# sort in descending to ascending
l.sort(reverse=True)
# remove particular element 7 l=[5,3,3,2,2,2,1]
l.remove(1)

Что такое Str?

  • STR – это последовательность символов, которые являются итерационными
  • Str неизменен
  • Элементы STR индексируются
s="Welcome to my blog follow me for more post like this."

Как создать и принять вклад в STR?

# Empty str
s=str()

Способы писать постоянную

# by using double quotes "
str1="Dev.to"
# by using single quotes '
str2='Follow me'
# by using """ 
str3="""Love the post"""

Как взять ввод от пользователя в STR?

# input() is a function used to take input from user return str
str=input("Enter a string")

Функция, предоставленная классом STR

s.replace()   : replace text by another text
s.index()     : get index of a particular text
s.count()     : count the occurrence of a given text
s.split()     : split str on the basis of given criteria returns 
                list
s.join()      : join each sequence elements separated by the given 
                criteria
s.startswith(): check whether the string start with the given text
s.endwith()   : check whether the string end with the given text
s.find()      : find some given text in the string
s.upper()     : convert the string to uppercase
s.lower()     : convert the string to lowercase
s.strip()     : remove extra white space from the left and right 
                of the string

STR содержит больше функций

Синтаксис

# Let first create a str
s='text'
# let replace 'tex' by 'res' gives 'rest' does not changes in s 
# return str object which i have again stored in s so it become 
# rest
s=s.replace('tex','res')
# find the index of s which is 2
s.find('s')
# count the occurrence of 'st' which is 1
s.count('st')
# split string on the basis of '' empty space means each char will 
# become element of the list l=['r','e','s','t']
l=s.split('')
# join l on the separating by ',' s="r,e,s,t"
s=','.join(l)
# check whether s starts with 'r,e,s' or not True
s.startswith('r,e,s')
# check whether s ends with 's,t' or not True
s.endswith('s,t')
# remove extra white space of '  My  ' using strip s='My'
s='  My  '.strip() 
# lowercase the string
s.lowercase()
# uppercase the string
s.uppercase()

Что такое кортеж?

  • Крупель неизменен
  • кортеж может хранить гетерогенный элемент
  • Элементы кортежа разделяются ‘,’
t=(1,'Comment','Share',1.5)

Самое распространенное сомнение 👇

Разница между кортежей и списком?

Как создать и принять вклад в кортеж?

Кортеж создается с использованием скобок ‘() «Внутри этого мы пишем элемент, разделенный« »,’

Как создать пустой кортеж

# by using tuple() function which create tuple object
t=tuple()
# by leaving the parenthesis empty
t=()

Как принять ввод в кортеж от пользователя?

# using List comprehension we convert the list into tuple using 
# tuple() function let check how
t=tuple([eval(i) for i in input("Enter data separated by commas ").split(',')])

Вы не можете добавить, изменить и удалять элемент в кортеже, это большая разница между кортежей и списком

Функции, предоставленные классом Tuple

Класс кортежей предоставляет только две функции

t.index(): get the index of particular text
t.count(): count the occurrence of given text

Синтаксис

# create a tuple
t=(1,2,3,4,'blogging',1)
# get the index of 3 in t which is 2
t.index(3)
# count the occurrence of 1 in t which is 2
t.count(1)

Методы встроения для любых последовательностей

len(): find the length of a given sequence
min(): finds the min value of the given sequence
max(): finds the min value of the given sequence
sum(): return the sum of the element of given sequence
sorted(): return list after sorting the given sequence

Синтаксис

# create a sequence
l=[2,5,1,4,3]
# find the len of l which is 5
len(l)
# find the max element which is 5
max(l)
# find the min element which is 1
min(l)
# find the sum which is 15
sum(l)
# sort l but no changes in l return list which is [1,2,3,4,5]
sorted(l)

Вывод

Этот пост поможет вам улучшить свои навыки Python в качестве новичка. Не забудьте Следуй за мной и дать Единорог Если этот пост информативен и полезен для вас. Если у вас есть какие -либо сомнения, прокомментируйте ниже. Этот пост создан по запросу @meenagupta5 Надеюсь, тебе это полюбишь

Читать далее:

5 Проект, чтобы освоить Python для начинающих

Ujjwal (UG Sep) ・ 23 августа ・ 2 мин прочитал

Как создать несколько PR в GitHub

Ujjwal (UG Sep) ・ 5 июля ・ 1 мин читал

Оригинал: “https://dev.to/ug/most-useful-sequences-in-python-for-beginners-3ac3”