
Practice 1:
a = 3str(a*3) + str(a)*3
结果:’9333’
a1=str('9333')a2=str(9) + str(3)+str(3)+str(3)a1,a2
结果:(‘9333’, ‘9333’)
dog = ["tom", "jack", "Collie", "Marry"]dog.reverse()dog
结果:
[‘Marry’, ‘Collie’, ‘jack’, ‘tom’]
[i for i in range(1,10) if i%2!=0]
结果:
[1, 3, 5, 7, 9]
- L=[1,2,’’,’my’,3,’name’,’is’,4,’katty’],利用循环语句和判断条件,分别输出列表中的字符串和数字。
方法一:
int_list=[]str_list=[]L=[1,2,'','my',3,'name','is',4,'katty']print(len(L))print(type(L[0]))for i in L:if type(i)== int:int_list.append(i)elif type(i)== str:str_list.append(i)print(int_list)print(str_list)
结果:
9
[1, 2, 3, 4]
[‘’, ‘my’, ‘name’, ‘is’, ‘katty’]
方法二:
L=[1,2,'','my',3,'name','is',4,'katty']print(L)for i in L:if type(i)== int:print(i)else :continuefor i in L:if type(i)== str:print(i)else :continue
结果:
[1, 2, ‘’, ‘my’, 3, ‘name’, ‘is’, 4, ‘katty’]
1
2
3
4
my
name
is
katty
- 定义一个求解阶乘的函数。
方法一:
def factorial(a):result = 1while a>0:result *=aa = a-1return resulta=4factorial(a)
方法二:
def factorial(x):result = 1for i in range(1,x+1):result *= ireturn resultfactorial(3)
利用函数和列表生成式,标记一个列表,奇数标记为1,偶数标记为2,并且统计一下奇数和偶数的数量。
例如:[1,4,2,4,2,9,5],得到[1,2,2,2,2,1,1] <br />方法一:
``` def translist(oldlist): newlist=[] odd_number = 0 even_number = 0 for i in oldlist:
if i%2 == 1:newlist.append(1)odd_number += 1elif i%2 == 0:newlist.append(2)even_number += 1
print(newlist) print(“奇数的个数为:”+ str(odd_number) +”,偶数的个数为:” +str(even_number))
oldlist = [1,4,2,4,2,9,5] translist(oldlist)
结果:<br />[1, 2, 2, 2, 2, 1, 1]<br />奇数的个数为:3,偶数的个数为:4方法二:
def func(i):
if i%2==0:
return 2
else:
return 1
l = [1,4,2,4,9,5]
[func(i) for i in l]
```
结果:
[1, 2, 2, 2, 1, 1]
