• 难度级别:简单

预测以下 Python 程序的输出。这些问题集将使您熟悉 Python 编程语言中的列表概念。

程序一:

list1 = ['physics', 'chemistry', 1997, 2000]

list2 = [1, 2, 3, 4, 5, 6, 7 ]

print "list1[0]: ", list1[0] #statement 1
print "list1[0]: ", list1[-2] #statement 2
print "list1[-2]: ", list1[1:] #statement 3
print "list2[1:5]: ", list2[1:5] #statement 4

输出:

list1[0]:  physics
list1[0]: 1997
list1[-2]: ['chemistry', 1997, 2000]
list2[1:5]: [2, 3, 4, 5]

说明:

要访问列表中的值,我们使用方括号与索引或索引一起进行切片,以获得该索引处可用的所需值。对于列表中的 N 个项目,索引的 MAX 值将是 N-1。

语句 1: 这将打印位于输出中索引 0 的项目。

语句 2: 这将打印位于索引 -2 的项目,即输出中的倒数第二个元素。

语句 3: 这将打印从索引 1 到列表末尾的项目。

语句 4: 这将打印位于列表索引 1 到 4 的项目。

程序二:

list1 = ['physics', 'chemistry', 1997, 2000]

print "list1[1][1]: ", list1[1][1] #statement 1

print "list1[1][-1]: ", list1[1][-1] #statement 2

输出:

list1[1][1]:  h
list1[1][-1]: y
  • 说明:
    在 python 中,我们可以对列表进行切片,但如果列表中的元素是字符串,我们也可以对其进行切片。声明 list[x][y] 将意味着“x”是列表中元素的索引,“y”是该字符串中实体的索引。

程序三:

list1 = [1998, 2002, 1997, 2000]
list2 = [2014, 2016, 1996, 2009]

print "list1 + list 2 = : ", list1 + list2 #statement 1

print "list1 * 2 = : ", list1 * 2 #statement 2

输出:

list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009] 
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]

说明:

当加法(+)运算符使用列表作为其操作数时,两个列表将连接起来。并且当列表 id 乘以常数 k>=0 时,相同的列表会在原始列表中附加 k 次。

程序四:

list1 = range(100, 110) #statement 1
print "index of element 105 is : ", list1.index(105) #statement 2

输出:

index of element 105 is :  5

解释:

语句 1: 将生成从 100 到 110 的数字并将所有这些数字附加到列表中。

语句2: 将列表list1中的索引值为105。

程序五:

list1 = [1, 2, 3, 4, 5]
list2 = list1

list2[0] = 0;

print "list1= : ", list1 #statement 2

输出:

list1= : [0, 2, 3, 4, 5]

解释:

在这个问题中,我们提供了一个对 list1 的引用,但是这两个列表有两个引用(list1 和 list2)。因此,对 list2 的任何更改都会影响原始列表。

如果大家发现任何不正确的地方,可以在下方评论区告诉我,互相学习,共同进步!