Python程序| Set 6的输出(列表)

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

null
  • 方案1

    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个项目,索引的最大值为N-1。 报表1: 这将打印输出中索引0处的项目。 报表2: 这将打印位于索引-2处的项目,即输出中的第二个最后一个元素。 报表3: 这将打印从索引1到列表末尾的项目。 报表4: 这将打印列表索引1到4中的项目。

  • 方案2

    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中,我们可以对列表进行切片,但如果列表中的元素是字符串,我们也可以对其进行切片。声明列表[x][y]意味着“x”是列表中元素的索引,“y”是该字符串中实体的索引。

  • 方案3

    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]
    
    

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

  • 方案4

    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: 将在列表1中给出索引值105。

  • 项目5

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

    
    

    输出:

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

    说明: 在这个问题中,我们用另一个名称list2提供了对list1的引用,但这两个列表是相同的,它们有两个引用(list1和list2)。因此,对列表2的任何更改都将影响原始列表。

本文由 阿维纳什·库马尔·辛格 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享