Python-简版List和Tuple

Python列表

Python list is a sequence of values, it can be any type, strings, numbers, floats, mixed content, or whatever. In this post, we will talk about Python list functions and how to create, add elements, append, reverse, and many other Python list functions.

原文网址:https://likegeeks.com/python-list-functions/

Create Python Lists/创建列表

To create a python list, enclose your elements in square brackets like this:

mylist = [1, 2, 3, 4, 5]

Your list could be strings like this:

mylist = ['one', 'two', 'three', 'four', 'five']

You can mix the elements types like this:

mylist = ['one', 20 , 5.5 , [10, 15], 'five']

You can write nested lists, which means lists inside lists live the above example.

Also, you can access any element of the list by its index which is zero based.

third_elem = mylist[2]

There are some similarities with strings. You can review the Python programming basics post.

Mutable Lists/改变列表

Lists are mutable because items can be changed or reordered.

If we have a list like the following:

mylist = ['one', 'two', 'three', 'four', 'five']

We can change the third item like this:

mylist[2] = "New item"

Now if you print the list, you should see the new list like this:

['one', 'two', 'New item', 'four', 'five']

If the index is a negative number, it counts from the last element.


The output of this code will be: five

 

Traverse a List/遍历列表

You can read the list elements using a for loop like this:


This way you can read the list elements. What about updating the elements:


The result will be:

[6, 7, 8, 9, 10]

The len() function is used to return the elements count, while the range() function returns the list of indices.

Keep in mind that, the nested list considered one element, regardless of how many elements inside it.


The result of the above code is 5

 

Slice a List/将列表切片

You can slice a list using (:) operator like this:


The result from the above code will be ['two', 'three']

If you remove the first number, the items start from the beginning. If you remove the second number, the items go to the end.

If you remove both numbers and remain the colon, the list will be copied.


The result of the above code will be:


Since lists are mutable, you can change elements using the slice operator:

mylist = ['one', 'two', 'three', 'four', 'five']
mylist[1:3] = ['Hello', 'Guys']
print(mylist)


The result will be:

['one', 'Hello', 'Guys', 'four', 'five']

Insert Into a List/在列表中插入元素

You can use the insert method to insert an element to the list like this:


The result will be:

[1, 'Hello', 2, 3, 4, 5]

Also, the index of the inserted element is zero based.

 

Append to a List/结尾追加元素

To append an element to a list, you can use the append method like this:


The result will be:

['one', 'two', 'three', 'four', 'five', 'new one']

You can append more than one element using extend method like this:


The result will be:

['one', 'two', 'three', 'four', 'five', 'Hello', 'Guys']

Of course, list2 will remain untouched.

Sort a List/排序一个列表

To sort a list, use the sort method.


The output will be:


 

Reverse a List/翻转一个列表

You can reverse the order of a Python list using the reverse method like this:


The output will be:

[5, 4, 3, 2, 1]

 

Index of an element/索引某元素位置

You can use the index method to get the element index like this:


The result will be:

1

If you have more than one element with the same name supplied to index function, it will return the first index that matches the supplied value.

Delete an Element/删除一个列表元素

You can delete an element by specifying the element index to the pop method like this:


The result will be:


If you don’t specify an index for the pop method, it will delete the last element.


The result will be:


You can remove an element using remove method like this:


The result will be:

['one', 'three', 'four', 'five']

You can use the del operator to remove an element like this:


The result will be:

['one', 'two', 'four', 'five']

Also, you can delete multiple elements using slice operator like this:


The result will be:

['one', 'four', 'five']

Aggregate Functions/内部函数

Python has some built-in aggregate functions like:

mylist = [5, 3, 2, 4, 1]
print(len(mylist))
print(min(mylist))
print(max(mylist))
print(sum(mylist))


The sum() function works on numeric items.

Also, you can use these functions (max(), len(), etc.) to deal with strings.

 

Compare Lists/比较列表

If you are using python 2, you can compare elements of two lists using the cmp function like this:


It will return -1 if no match, or it will return 1 if it matches.

You can compare two lists using the == operator in Python 3 like this:


The result will be:

No match

Math Operations On Lists/列表上的运算符

You can use the plus (+) to merge lists like this:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)


The output will be:

[1, 2, 3, 4, 5, 6]

Also, you can repeat a list using the multiply operator like this:


The result will be:

[1, 2, 3, 1, 2, 3]

Lists and Strings/列表和字符串的关系

To convert a string to separate characters, you can use the list function like this:


The result will be:

['L', 'i', 'k', 'e', 'G', 'e', 'e', 'k', 's']

The list function is used to break a string into single letters as shown.

You can use the split method to split the text into words like this:


The result will be:

['Welcome', 'to', 'likegeeks', 'website']

As you see, the returned output is a normal list, you can get any word by index and manipulate it.

What about using another splitter other than space?


The result will be the same like the above example:

['Welcome', 'to', 'likegeeks', 'website']

Join a List

The opposite process of splitting a string to a list of strings is to join them to make a string.

You join list elements to make one string using the join method like this:


The output will be:

Welcome to likegeeks website

Aliasing

When two variables referencing the same object like this:


Aliasing means the object has more than one reference with more than one name.

Look at the following example to understand how mutable lists change:


The result will be:

['Welcome', 'to', 'likegeeks', 'page']

We made a change to list2, but since they are referencing to the same object and that object is mutable, the changes affect the original list.

You shouldn’t do aliasing when working with lists.

Working with a python list is very easy as we’ve seen. I hope you find the post useful and interesting. Keep coming back.

Python 列表

Python囊括了大量的复合数据类型,用于组织其它数值。最有用的是列表,即写在方括号之间、用逗号分隔开的数值列表。列表内的项目不必全是相同的类型。

>>> a = ['spam', 'eggs', 100, 1234]
a
['spam', 'eggs', 100, 1234]
squares = [1, 4, 9, 16, 25]
squares
[1, 4, 9, 16, 25]

像字符串一样,列表可以被索引和切片:

squares[0]  # 索引返回的指定项
1
squares[-1]
25
squares[-3:]  # 切割列表并返回新的列表
[9, 16, 25]

所有的分切操作返回一个包含有所需元素的新列表。如下例中,分切将返回列表 squares 的一个拷贝:

>>> squares[:]
[1, 4, 9, 16, 25]

列表还支持拼接操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python 字符串是固定的,列表可以改变其中的元素:

>>> cubes = [1, 8, 27, 65, 125]
4  3
64
cubes[3] = 64  # 修改列表值
cubes
[1, 8, 27, 64, 125]

您也可以通过使用append()方法在列表的末尾添加新项:

>>> cubes.append(216)  # cube列表中添加新值
cubes.append(7  3)  #  cube列表中添加第七个值
cubes
[1, 8, 27, 64, 125, 216, 343]

你也可以修改指定区间的列表值:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']

#替换一些值

letters[2:5] = ['C', 'D', 'E'] letters ['a', 'b', 'C', 'D', 'E', 'f', 'g']

#移除值

letters[2:5] = []

letters ['a', 'b', 'f', 'g']

#清除列表

letters[:] = [] letters []

内置函数 len() 用于统计列表:

>>> letters = ['a', 'b', 'c', 'd']
len(letters)
4

也可以使用嵌套列表(在列表里创建其它列表),例如:

>>> a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
x
[['a', 'b', 'c'], [1, 2, 3]]
x[0]
['a', 'b', 'c']
x[0][1]
'b'



Python3 元组

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

如下实例:

tup1 = ('Google', 'W3CSchool', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

创建空元组

tup1 = ();

元组中只包含一个元素时,需要在元素后面添加逗号

tup1 = (50,);

元组与字符串类似,下标索引从0开始,可以进行截取,组合等。


访问元组

元组可以使用下标索引来访问元组中的值,如下实例:

#!/usr/bin/python3

tup1 = ('Google', 'W3CSchool', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

以上实例输出结果:

tup1[0]:  Google
tup2[1:5]:  (2, 3, 4, 5)

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

#!/usr/bin/python3

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')

# 以下修改元组元素操作是非法的。
# tup1[0] = 100

# 创建一个新的元组
tup3 = tup1 + tup2;
print (tup3)

以上实例输出结果:

(12, 34.56, 'abc', 'xyz')

删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

#!/usr/bin/python3

tup = ('Google', 'W3CSchool', 1997, 2000)

print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)

以上实例元组被删除后,输出变量会有异常信息,输出如下所示:

删除后的元组 tup : 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined

元组运算符

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式结果描述
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print x, 1 2 3 迭代

元组索引,截取

因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,如下所示:

元组:

L = ('Google', 'Taobao', 'W3CSchool')
Python 表达式结果描述
L[2] 'W3CSchool!' 读取第三个元素
L[-2] 'Taobao' 反向读取;读取倒数第二个元素
L[1:] ('Taobao', 'W3CSchool!') 截取元素,从第二个开始后的所有元素。

运行实例如下:

>>> L = ('Google', 'Taobao', 'W3CSchool')
>>> L[2]
'W3CSchool'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao', 'W3CSchool')

元组内置函数

Python元组包含了以下内置函数

序号方法及描述实例
1 len(tuple)
计算元组元素个数。
>>> tuple1 = ('Google', 'W3CSchool', 'Taobao')
>>> len(tuple1)
3
>>> 
2 max(tuple)
返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>> 
3 min(tuple)
返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>> 
4 tuple(seq)
将列表转换为元组。
>>> list1= ['Google', 'Taobao', 'W3CSchool', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'W3CSchool', 'Baidu')


原文地址:https://www.cnblogs.com/augustone/p/11333933.html