Python 计算列表元素之积
def multiplyList(mylist):
result = 1
for x in mylist:
result = result * x
return result
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(multiplyList(list1))
print(multiplyList(list2))
输出结果
6
120
Python 判断元素是否在列表中存在
test_list = [1, 3, 5, 7, 9, 11, 13, 15, 4]
print("查看4是否在列表之中(使用循环):")
for i in test_list:
if(i==4):
print("4在列表之中")
print("查看4是否在列表之中(使用in关键字):")
if(4 in test_list):
print("存在")
输出结果
查看4是否在列表之中(使用循环):
4在列表之中
查看4是否在列表之中(使用in关键字):
存在
定义一个类
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name + " is sitting")
def roll_over(self):
print(str(self.name + " is rolling over"))
#print("my dog name is " + my_dog.name)
#print("my dog age is " + str(my_dog.age) )
my_dog = Dog('sherry',6)
my_dog.sit()
my_dog.roll_over()
Dog是一个类,_init_表示调用默认的实例来传参。
这个self就相当于后面创建的实例,self中的变量可以供类中的所有方法使用。
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odermeter_reading = 23
def get_describe_name(self):
long_time = str(self.year) + ' ' + self.make + ' ' + self.model
return long_time.title()
def read_odermeter(self):
print("This car has " + str(self.odermeter_reading) + ' miles on it')
def update_odermeter(self, mileage):
if mileage >= self.odermeter_reading:
self.odermeter_reading = mileage
else:
print("you can't roll back an odometer")
my_car = Car('mood','vehel',26)
print(my_car.get_describe_name())
my_car.update_odermeter(22)
my_car.read_odermeter()
Python 使用正则表达式提取字符串中的 URL
import re
def Find(string):
# findall() 查找匹配正则表达式的字符串
url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
return url
string = 'Runoob 的网页地址为:https://www.runoob.com,Google 的网页地址为:https://www.google.com'
print("Urls: ", Find(string))
Urls: [‘https://www.runoob.com’, ‘https://www.google.com’]