l1 = [‘b’,‘c’,‘d’,‘c’,‘a’,‘a’]
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)
也可以这样写:
l1 = [‘b’,‘c’,‘d’,‘c’,‘a’,‘a’]
l2 = sorted(set(l1),key=l1.index)
print(l2)
也可以用遍历:
l1 = [‘b’,‘c’,‘d’,‘c’,‘a’,‘a’]
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
print(l2)
14.给定两个list A,B ,请用找出A,B中相同与不同的元素
A,B 中相同元素: print(set(A)&set(B))
A,B 中不同元素: print(set(A)^set(B))
企业面试题
15.python新式类和经典类的区别?
a. 在python里凡是继承了object的类,都是新式类
b. Python3里只有新式类
c. Python2里面继承object的是新式类,没有写父类的是经典类
d. 经典类目前在Python里基本没有应用
16.python中内置的数据结构有几种?
a. 整型 int、 长整型 long、浮点型 float、 复数 complex
b. 字符串 str、 列表 list、 元祖 tuple
c. 字典 dict 、 集合 set
d. Python3 中没有 long,只有无限精度的 int
17.python如何实现单例模式?请写出两种实现方式?
第一种方法:使用装饰器
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True
第二种方法:使用基类 New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例
class Singleton(object):
def new(cls, *args, **kwargs):
if not hasattr(cls, ‘_instance’):
cls._instance = super(Singleton, cls).new(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True
第三种方法:元类,元类是用于创建类对象的类,类对象创建实例对象时一定要调用call方法,因此在调用call时候保证始终只创建一个实例即可,type是python的元类
class Singleton(type):
def call(cls, *args, **kwargs):
if not hasattr(cls, ‘_instance’):
cls._instance = super(Singleton, cls).call(*args, **kwargs)
return cls._instance
Python2
class Foo(object):
metaclass = Singleton
Python3
class Foo(metaclass=Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True
18.反转一个整数,例如-123 --> -321
class Solution(object):
def reverse(self,x):
if -10<x<10:
return x
str_x = str(x)
if str_x[0] !=“-”:
str_x = str_x[::-1]
x = int(str_x)
else:
str_x = str_x[1:][::-1]
x = in