1、l=[1,1,6,3,1,5,2]
去重,至少两种方法
1.
l = [1, 1, 6, 3, 1, 5, 2]
l = set(l)
2.
l = [1, 1, 6, 3, 1, 5, 2]
k = []
for i in l:
if i not in k:
k.append(i)
print(k)
2、实现字符串反转 输入str=”string”输出’gnirts’
三种方法
1.
str1 = "string"
list1 = list(str1)
list1.reverse()
str2 = ''.join(list1)
print(str2)
2.
str1="string"
print(str1[::-1])
3.
str1="string"
l = list(str1)
result = ""
while len(l)>0:
result += l.pop()
print(result)
3、一行代码实现对列表a中的偶数位置的元素进行加3后求和
b = reduce(lambda x,y: x + y, [i + 3 for i in a if i % 2 == 0])
4、List = [-2, 1, 3, -6],如何实现以绝对值大小从小到大将 List 中内容排序
List = [-2, 1, 3, -6]
List.sort(key=abs)
print(List)
5、list 对象 alist [{‘name’:’a’,’age’:20},{‘name’:’b’,’age’:30},{‘name’:’c’,’age’:25}], 请按 alist 中元素的age 由大到小排序;
alist = [{'name': 'a', 'age': 20}, {'name': 'b', 'age': 30}, {'name': 'c', 'age': 25}]
alist.sort(key= lambda a: a['age'])
print(alist)
6、将字符串:”k:1|k1:2|k2:3|k3:4”,处理成 python 字典:{‘k’:’1’, ‘k1’:’2’, ‘k2’:’3’,’k3’:’4’ }
str1 = "k:1|k1:2|k2:3|k3:4"
list1 = str1.split('|')
list2 = []
dict1 = {}
for i in list1:
list2 = i.split(':')
dict1.update({str(list2[0]): str(list2[1])})
print(dict1)
7、定义一个列表的操作类:Listinfo
包括的方法:
1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型]
2 列表元素取值:get_key(num) [num:整数类型]
3 列表合并:update_list(list) [list:列表类型]
4 删除并且返回最后一个元素:del_key()
class Listinfo():
def __init__(self, list):
self.list1 = list
def add_key(self, keyname):
if isinstance(keyname, (str, int)):
self.list1.append(keyname)
return self.list1
else:
return 'error'
def get_key(self, num):
if num >= 0 and num < len(self.list1):
return self.list1[num]
else:
return 'error'
def update_list(self, list2):
self.list1.extend(list2)
return self.list1
def del_key(self):
if len(self.list1) >= 0:
return self.list1.pop(-1)
else:
return 'error'
8、写单例,至少两种形式
new
class Singleton():
__A = None
__has_init = False
def __new__(cls, *args, **kwargs):
if cls.__A is None:
cls.__A = super().__new__(cls)
return cls.__A
装饰器
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x