Python(4)操作列表

2021-08-09 18:12:36 字數 3208 閱讀 8550

使用for迴圈

magicians=['a','b','c']

for magician in magicians:

print(magician.title()+",that was a great trick!")

print("i can't wait to see you,"+magician.title()+".\n")

print("thank you,everyone!\n")

range函式

for value in range(1,6):

print(value)

numbers=list(range(1,6)) #轉為列表

print (numbers)

even_numbers=list(range(1,10,2))#列印奇數

print (even_numbers)

print

"\n"

squares=

for value in range(1,11):

square=value**2

#計算平方

print(squares)

print

"\n"

對列表進行簡單的統計計算

digits=range(1,20,3)

print digits

print

min(digits)

print

max(digits)

print sum(digits)

print

"\n"

列表解析

squares=[value**2

for value in range(1,11)]

print(squares)

print

"\n"

練習

#

for int in range(1,20):

print int

print

"\n"

'''#

for int in range(1,1000000):

print int

'''#

count=list(range(1,1000000))

print min(count)

print max(count)

print sum(count)

print

"\n"

#int=list(range(1,20,2))

print int

for int in range(1,20,2):

print int

print

"\n"

#count=[value**3

for value in range (1,10)]

print count

#counts=

for value in range(1,10):

count=value**3

print counts

切片

players=['a','b','c','d']

print (players[1:3])

print (players[:3])

print (players[1:])

print (players[-3:])#列印最後三個

print (players[:]) #列印所有的

print ('\n'+"here are the first three pop star:")

for player in players[:3]:

print (player.title())

用切片複製列表

my_food=['aa','bb','cc']

friend_food=my_food[:]

print ('\n'+"i like these foods:"+str(my_food))

print ('she likes these foods:'+str(friend_food))

練習

#

magicians=['a','b','c','d','e']

print ('\n'+"here are the first three pop star:")

print (magicians[2:4])

#my_pizza=['aa','bb','cc']

friend_pizza=my_pizza[:]

print ('\n'+"i like these pizza:"+str(my_food))

print ('she likes these pizza:')

for pizza in friend_pizza:

print pizza

建立元組,元組元素不可以被修

dimensions=(200,50)

print

(dimensions[0])

print

(dimensions[1])

元組元素,會報錯

dimensions[0]=250
遍歷元組所有元素

print

"\noriginal dimensions:"

for dimension in dimensions:

print(dimension)

通過給儲存元組的變數賦值來改變元組變數

print 「\nmodified dimensions:」

dimensions=(400,250)

for dimension in dimensions:

print(dimension)

python(4) 列表 元組 字典的使用

1.編寫程式,輸入任意大的自然數,輸出各位數字之和。a input 請輸入自然數 print sum map int a 2.編寫程式,輸入兩個集合 seta 和 setb,分別輸出它們的交集 並集和差集 seta setb。set a set hello my friend set b set h...

Python(4) 函式與模組

def hi print hello,world for i in range 0,4 1 hi def listsum l res 0 for i in l res res i return res l2 1,2,3,4,5,6,7,8,9,10 sum2 listsum l2 print sum...

python 4輸入和輸出

4 輸入和輸出 4.1 輸出 1.普通的輸出 電力的輸出,音訊的輸出 2.軟體中輸出 例如登入是輸入使用者名稱和密碼,如果有乙個不正確,會出現乙個對話方塊,提示使用者重新輸入使用者名稱和密碼。3.python中輸出 列印提示print hello word 4.格式化的輸出 print hello ...