# 写一个函数,实现通过交换字典中的Key和Value生成新的一个字典
如字典a = {"name":"rotate", "age":29, "score":88},经过交换后变成{"rotate":"name", 29:"age", 88:"score"}。
def pDict(): a = {"name":"rotate", "age":29, "score":88} b = {v:k for k,v in a.items()} print(b) pDict()
输出结果:{'rotate': 'name', 29: 'age', 88: 'score'}
#列表 plist = [734, 8465, 94, 4345, 653, 266, 665, 5],写一个函数,按照如下的字符串形式 "94846573466565354345266" 输出。
def list_sort(plist): list = [str(x) for x in plist] #将数值列表转换成字符串列表 ['734', '8465', '94', '4345', '653', '266', '665', '5'] list.sort(reverse=True) #sort排序再反排序 ['94', '8465', '734', '665', '653', '5', '4345', '266']
list1 = ''.join(list) #List列表转为Str字符串
return list1
plist = [734, 8465, 94, 4345, 653, 266, 665, 5]
result=list_sort(plist) print(result)
输出结果:94846573466565354345266
#找出字符串中出现的第一个不重复的字符.
#coding=utf-8 def findFirstCharacter(pstr): for i in range(len(pstr)): if pstr.index(pstr[i]) == pstr.rindex(pstr[i]): return pstr[i] return None pstr = "djkljjkjkjlda" result = findFirstCharacter(pstr) print(result) 输出结果:a
# 判断字符串是否是一个ip地址(ipv4地址,如 192.168.1.1)
#coding=utf-8 def isIpAddress(ip_address): if not isinstance(ip_address,str): print("ilegal input,please enter ip again")
return False if ip_address.count('.') != 3: return False else: ip = ip_address.split('.') for i in ip: try: one_ip = int(i) if one_ip>=0 and one_ip <=255: pass else: print(one_ip) return False except: print( "{0} is not a number.".format(i)) return False return True if __name__ == "__main__": while True: myIp = input("please enter ip: ") if isIpAddress(myIp): print("{0} is a legal ip".format(myIp)) else: print("this is not a legal ip")
#统计字符串中的字符出现的次数
pstr = "hdkfjowfojlkjal" pDict = {} for s in pstr: PDict[s] = pstr.count(s) print(PDict)
#删除重复的二维列表
二维列表中,里面元素能用元组则用元组