位置:首頁(yè) > 軟件操作教程 > 編程開(kāi)發(fā) > Python > 問(wèn)題詳情

python經(jīng)典實(shí)例——列表

提問(wèn)人:楊紫紅發(fā)布時(shí)間:2020-11-26
#! /usr/bin/python
# -*- coding: utf8 -*-
#列表類(lèi)似Javascript的數(shù)組,方便易用

#定義元組
word=['a','b','c','d','e','f','g']

#如何通過(guò)索引訪問(wèn)元組里的元素
a=word[2]
print ("a is: "+a)
b=word[1:3]
print ("b is: ")
print (b) # index 1 and 2 elements of word.
c=word[:2]
print ("c is: ")
print (c) # index 0 and 1 elements of word.
d=word[0:]
print ("d is: ")
print (d) # All elements of word.

#元組可以合并
e=word[:2]+word[2:]
print ("e is: ")
print (e) # All elements of word.
f=word[-1]
print ("f is: ")
print (f) # The last elements of word.
g=word[-4:-2]
print ("g is: ")
print (g) # index 3 and 4 elements of word.
h=word[-2:]
print ("h is: ")
print (h) # The last two elements.
i=word[:-2]
print ("i is: ")
print (i) # Everything except the last two characters
l=len(word)
print ("Length of word is: "+ str(l))
print ("Adds new element")
word.append('h')
print (word)

#刪除元素
del word[0]
print (word)
del word[1:3]
print (word)

'''
知識(shí)點(diǎn):

    * 列表長(zhǎng)度是動(dòng)態(tài)的,可任意添加刪除元素.
    * 用索引可以很方便訪問(wèn)元素,甚至返回一個(gè)子列表
    * 更多方法請(qǐng)參考Python的文檔
'''

繼續(xù)查找其他問(wèn)題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部