Python-列表

时间:2020-02-23 14:42:10  来源:igfitidea点击:

在本教程中,我们将学习Python中的列表。

我们在Python-数据类型教程中简要讨论了列表。

什么是列表?

列表是项目的有序序列。
我们使用方括号[]在Python中创建列表。

列表中的各项以逗号分隔,并且可以是多种类型,例如整数,浮点数,字符串,布尔值,复数。

列表中的项目可以重复多次。

在下面的示例中,我们将创建一个整数列表。

myList = [1, 2, 3]

list()构造函数

我们使用list()构造函数在Python中创建一个列表。

# list
myList = list((1, 3.14, 'theitroadtheitroad', 1+2j, True))

print("Type of myList:", type(myList))
print(myList)
Type of myList: <class 'list'>
[1, 3.14, 'theitroadtheitroad', (1+2j), True]

访问列表项

对列表中的项目建立索引,列表的第一项获得索引0,列表的第二项获得索引1,依此类推。

与其他编程语言(如C和Java)一样,Python中列表的索引是整数值。

如果列表包含10个项目,则最后一个项目将位于索引(n-1)处,即9。

We access list items using list[index]notation.

其中," list"代表列表变量,而" index"则是我们要访问的项目的索引。

在以下示例中,我们将打印给定列表的索引1和3处的项目。

# list
myList = [1, "two", True, 3.14, 2+3j]

print(myList[1])    # "two"
print(myList[3])    # 3.14

处理列表项

我们使用" list [index] = value"表示法来操纵(更改)列表项。

其中," list"表示列表变量," index"是我们要更改的项目的索引,而" value"是我们要在给定索引处分配给列表项的新值。

在下面的Python程序中,我们将更改索引3的值。

# list
myList = [1, "two", True, 3.14, 2+3j]

print("Before", myList)

# change
myList[2] = False

print("After", myList)

我们将获得以下输出。

Before [1, 'two', True, 3.14, (2+3j)]
After [1, 'two', False, 3.14, (2+3j)]

列表项计数

我们可以使用len()方法找到给定列表中存在的项目总数。

在下面的Python程序中,我们将打印出给定列表中存在的项目总数。

# list
myList = [1, "two", True, 3.14, 2+3j]

print("Total number of items:", len(myList))

我们将获得以下输出。

Total number of items: 5

遍历列表项

我们可以使用for循环和while循环遍历给定列表的项目。

在下面的示例中,我们使用for循环打印给定列表的所有项目。

# list
myList = [1, "two", True, 3.14, 2+3j]

for i in myList:
    print(i)

上面的Python程序将为我们提供以下输出。

1
two
True
3.14
(2+3j)

我们还可以使用while循环来达到相同的结果。

# list
myList = [1, "two", True, 3.14, 2+3j]

i = 0
while i < len(myList):
  print(myList[i])
  i += 1

检查列表项

如果要检查列表中是否存在给定项目,则使用in-成员运算符。

如果我们要查找的项目存在于列表中,那么我们将得到" True",否则为" False"。

在下面的Python程序中,我们检查给定列表中是否存在3和" Hello"。

# list
myList = ["Food", 2, 3.14, "Hello", False]

# is 3 present
if 3 in myList:
    print("3 is present in the list")
else:
    print("3 is not present in the list")

# is "Hello" present
if "Hello" in myList:
    print("Hello is present in the list")
else:
    print("Hello is not present in the list")

该程序将为我们提供以下输出。

3 is not present in the list
Hello is present in the list