
#(a)
def list_printer(aList):
print(aList)
for x in aList:
print(x,end= ' ')
print()
#(b)
def list_printer_r(aList):
rList = aList[::-1]
print(rList)
for x in rList:
print(x,end = ' ')
print()
#(c)
def my_len(aList):
counter =0
for x in aList:
counter = counter +1
return counter
aList = [1,2,3,4,5,6,7,8]
list_printer(aList)
list_printer_r(aList)
print('the len of aList is '+str(my_len(aList)))


#(a)
a = [1,2,3,4,5,6,7,8]
b = a
b[1] = 9999
print('now print a -> ',end ='')
print(a)
c = a[:]
c[2] = -666
print('now print a -> ',end ='')
print(a)
def set_first_elem_to_zero(l):
l[1] = 0
set_first_elem_to_zero(a)
print('now print a -> ',end ='')
print(a)
在 b = a中, a,b会共享一个存储空间,所以对b的修改会引起a的改变,但是在c = a[:]中,先创建一个副本,再传递,这样两者就在两个不同的空间了,c的修改也不会引起a的改变,函数修改那个类似于b = a。

a = [[]] * 3
b = [[] for _ in range(3)]
for i in a:
print(i,end = ' ')
print()
for x in b:
print(x,end = ' ')
print()
没有不同。。

def list_and_func(aList,index):
aList[index] = 0
aList = [1,2,3,4,5]
print(aList)
list_and_func(aList,3)
print(aList)
import math
def count_prime(n,aList):
if(n >= 2 ):
aList.append(2)
if(n >= 3):
aList.append(3)
for x in range(4,n+1):
if((x-1)%6 !=0 and (x+1)%6 != 0 ):
continue
flag = True
for i in range(2,int(math.sqrt(n))):
if(x%i == 0):
flag = False
if(flag == True):
aList.append(x)
else:
flag = True
def count_prime_2(n,aList):
if(n >= 1):
aList.append(2)
if(n >= 2):
aList.append(3)
num_found = 2
x = 5
while(True):
if((x-1)%6 !=0 and (x+1)%6 != 0 ):
x = x+1
continue
flag = True
for i in range(2,int(math.sqrt(n))):
if(x%i == 0):
flag = False
if(flag == True):
num_found = num_found +1
aList.append(x)
if(num_found == n):
break
else:
flag = True
x = x+1
aList = []
count_prime(99,aList)
bList = []
count_prime_2(5,bList)
print(aList)
print(bList)
本文通过几个具体的Python代码示例,介绍了列表的基本操作方法,包括正向和逆向打印列表、计算列表长度等,并探讨了列表与变量之间的引用关系及如何避免修改原列表。此外,还展示了如何使用函数来实现特定功能,如设置列表首个元素为零、统计素数等。
549

被折叠的 条评论
为什么被折叠?



