1.python代码实现删除一个list里面的重复元素
*方法一:*for循环遍历
list1=[1,1,2,3,4,4,5]
result=[]
re=[]
for i in list1:
if i not in result:
result.append(i)
else:
re.append(i)
print(result,'\n',re)
result输出删除重复元素后的list: [1, 2, 3, 4, 5]
re输出重复元素: [1, 4]
*方法二:*字典的fromkeys()
a=[1,1,2,3,4,4,5]
b=dict.fromkeys(a)
print(b)
c=list(b.keys())
print(c)
b是创建的新字典,c:[1, 2, 3, 4, 5]
*方法三:*set()函数直接对list删除重复元素
list2=[1,1,2,3,4,4,5]
list2=list(set(list2))
print(list2)
2.Given an array of integers
使用numpy数据库
以下a,b是两种方法输出的列阵,效果一样
import numpy as np
a=np.arange(0,20,1,dtype=int)
b=np.array(range(0,20))
3.字符串”123″转换成123,不使用内置api,例如int()
from functools import reduce
a='123'
def str2float(a):
return reduce(lambda x,y:x+int2dec(y),map(str2int,a.split('.')))
def char2num(a):
return{'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[a]
def str2int(a):
return reduce(lambda x,y:x*10+y,map(char2num,a))
def intLen(i):
return len('%d'%i)
def int2dec(i):
return i/(10**intLen(i))
print(str2float(a))
4.写一个类,并让它尽可能多的支持操作符?
class employee:
def __init__(self,name,age,salary):
self.name=name
self.age=age
self.salary=salary
def getname(self):
print (self.name)
def getage(self):
print (self.age)
def getsalary(self):
print (self.salary[0]+self.salary[1])
emp1=employee("张三",30,[15000,300])
emp1.getname()
print(getattr(emp1,'name'))
print(dir(emp1)) #获得类的所有属性和方法
5.用一行python代码写出1+2+3+10248
from functools import reduce
sum=reduce(lambda x,y:x+y,[1,2,3,10248])
6.求出列表所有奇数并构造新列表
def oddlist(l):
new=[]
for i in range(len(l)):
if l[i]%2 ==1:
odd=l[i]
new.append(odd)
print(new)
return