What sequences are lists, tuples, and strings in Python?

青灯夜游
Release: 2020-08-29 16:20:49
Original
23231 people have browsed it

Lists, tuples, and strings are ordered sequences of Python; lists are mutable objects, and tuples and strings are immutable objects. Each element in the sequence is assigned a number, which is its position, or index, with the first index being 0, the second index being 1, and so on.

What sequences are lists, tuples, and strings in Python?

# Sequence is the most basic data structure in Python. Each element in the sequence is assigned a number - its position, or index, with the first index being 0, the second index being 1, and so on.

Operations that can be performed on sequences include indexing, slicing, adding, multiplying, and checking members. Additionally, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements.

Lists, tuples, and strings are ordered sequences in python; lists are mutable objects, while tuples and strings are immutable objects.

List (list)

A list is an ordered sequence containing 0 or more object references and supports the same sharding and steps as strings and tuples. distance grammar. Unlike strings and tuples, lists are mutable, so we can delete or replace items in the list, insert, replace, or delete slices in the list.

The list data type can be called as a function, list()--calling without parameters will return an empty list; with a list parameter, a shallow copy of the parameter will be returned; for any other parameters, then attempts to convert the given object to a list. The function value accepts a parameter. Lists can also be created without using the list() function. An empty list can be created using empty square brackets. A list containing one or more items can be created using a comma-separated sequence of data items (enclosed in []).

Methods provided by lists:

What sequences are lists, tuples, and strings in Python?

#Any iterable (list, tuple, etc.) data type can be split using the sequence split operator ,Right now:* . When used to assign two or more variables to the left of the operator, one of which is introduced with *, the data item will be assigned to that variable, and all remaining data items will be assigned to the asterisked variable, given below Some examples:

What sequences are lists, tuples, and strings in Python?

#When the sequence splitting operator is used in this way, the expression *rest and similar expressions are called asterisked expressions.

Python also has a related concept: asterisked parameters.

What sequences are lists, tuples, and strings in Python?

Scientific research performs iterative processing on the data items in the list. The syntax format used is for item in L:. If you need to change the data items in the list, the usual method is as follows:

for i in range(len(L)):
L[i] = process(L[i])
Copy after login

Since the list supports sharding, in several cases, the same function can be accomplished using sharding or some list method. For example: given the list woods=['Cedar','Yew','Fir'], we can extend the list in the following two ways:

woods+=['Kauri','Larch']    | woods.extend(['Kauri','Larch'])
Copy after login

For the above two methods, the results obtained are both lists ['Cedar','Yew','Fir','Kauri','Larch'].

Using the list.append() method, a single data item can be added to the end of the list. Data items can be inserted into the list at any index position using the list.insert() method (or assigning to a 0-length slice). For example, given the list woods=['Cedar','Yew','Fir','Spruce'], we can insert a new data item at index position 2 (that is, as the third item of the list), The following two methods can be implemented:

woods[2:2] = ['Pine'] |  woods.insert(2,'Pine')
Copy after login

The results obtained by the above two methods are the list ['Cedar','Yew','Pine','Fir','Spruce'].

By assigning a value to the object at a specific index position, a single data item in the list can be replaced, for example, woods[2]='Redwood'. By assigning iterable to a shard, you can replace the entire shard, for example, woods[1:3]=['Spruce','Sugi','Rimu'], and the shard iterables do not have to be of equal length. In all these cases, the shard's data items are removed and the iterable's data items are inserted. If the iterable contains fewer items than the fragment to be replaced, this operation makes the category shorter; otherwise, the list becomes. The following example:

What sequences are lists, tuples, and strings in Python?

For complex lists, you can use a for...in loop to create them. For example, assuming you need to generate a list of leap years within a given time range, you can use the following Statement:

 leaps = []
 for year in range(1900,1940):
  if (year%4 == 0 and year %100 !=0) or (year % 400 ==0):
    leaps.append(year)
Copy after login

Two expressions:

expression for item in iterable
    expression for item in  iterable if condition
Copy after login

Tuple

元组是个有序的序列,其中包含0个或多个对象引用。元组支持与字符串一样的分片与步距的语法,这使得从元组中提取数据项比较容易。元组也是固定的,不能替换或删除其中包含的任意数据项。如果需要修改有序序列,我们应该使用类别而非元组。如果要对元组进行修改,可以使用list()转换函数将其转换为列表,之后在产生的列表之上进行适当修改。

tuple数据类型可以作为一个函数进行调用,tuple()---不指定参数时将返回一个空元组,使用tuple作为参数时将返回该参数的浅拷贝,对其他任意参数,将尝试把给定的对象转换为tuple类型。该函数最多只能接受一个参数。元组也可以使用tuple()函数创建,空元组是使用空圆括号()创建的,包含一个或多个项的元组则可以使用逗号分隔进行创建。

元组只提供了两种方法:t.count(x),返回对象x在元组中出现的次数;t.index(x),返回对象在元组t中出现的最左边位置。

元组可以使用操作符+(连接)、*(赋值)与 [](分片),要可以使用in 与not in 来测试成员关系。

下面给出几个分片实例:

What sequences are lists, tuples, and strings in Python?

上面这些处理过程对字符串、列表以及人员其他序列类型都是一样的

What sequences are lists, tuples, and strings in Python?

要构成一个亿元组,逗号是必须的,这里red字符串地方我们必须同时使用逗号与圆括号。

1.1 命名的元组

命名的元组与普通元组一样,有相同的表现特征,其添加的功能就是可以根据名称引用元组中的项,就像根据索引位置一样,这一功能使我们可以创建数据项的聚集。

collections 模块提供了 namedtuple()函数,该函数用于创建自定义的元组数据类型,例如:

What sequences are lists, tuples, and strings in Python?

collections.namedtuple()的第一个参数是想要创建的自定义元组数据类型的名称,第二个参数是一个字符串,其中包含使用空格分割的名称,每个名称代表该元组数据类型的一项。该函数返回一个自定义的类(数据类型),用于创建命名的元组。因此,这一情况下,我们将sale与任何其他python类一样看待,并创建类型为sale的对象,如:

What sequences are lists, tuples, and strings in Python?

这里我们厂家了包含两个sale项的列表,也就是包含两个自定义元组。我们也可以使用索引位置来引用元组中的项----比如,第一个销售项的价格为sales[0][-1],但我们呢也可以使用名称进行引用,这样会更加清晰:

What sequences are lists, tuples, and strings in Python?

命名的元组提供的清晰与便利通常都是有用的,比如,下面另一个例子:

What sequences are lists, tuples, and strings in Python?

私有方法namedtuple._asdict()返回的是键-值对的映射,其中每个键都是元组元素的名称,值则是对应的值,我们使用映射拆分将映射转换为str.format()方法的键-值参数。

“{manufacturer} {model}”.format(**aircraft._asdict())

字符串

str,字符串在python中是有序序列,这意味着字符串在python中可以做很多操作,比如slice。不过有一点是字符串中某部分无法进行修改,因为是不可变对象。

字符串经常碰到的一个问题就是怎么把 字符串倒序输出。

这时候我们就可以把slice用到字符串中,编写一个倒序输出的函数如下:

def reverse(x):
    if not isinstance(x,basestring):
       raise TypeError ("bad type");
    else:
        return x[::-1]
Copy after login

isinstance是用来判断参数是否是字符串,如果不是的话将会报错。

basestring是str和unicode的父类,可以用来分辨是不是字符串的类型。

推荐学习:Python视频教程

The above is the detailed content of What sequences are lists, tuples, and strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template