python编程如何求2000到2500闰年?_Python教程
python编程求2000到2500闰年的方法:首先定义年份【i=2000】;然后用while循环判断是否在2500内;接着若年份可被40整除且不被100整除,则是闰年,若年份可被400整除,则是闰年。
python字典中如何一键多值的写入?
python字典中一键多值写入的方法:
1、循环写入字典key、value、删除指定的键值对:
原文本‘jp_url.txt’每行元素以逗号分隔:
host_key,product_id,product_name,cont_start,cont_end ah2.zhangyue.com,100002,掌阅,bookId=,&startChapterId ih2.ireader.com,100002,掌阅,bid=,& www.ireader.com,100002,掌阅,&bid=,&cid m.zhangyue.com,100002,掌阅,readbook/,/ c13.shuqireader.com,100003,书旗,bookId=,&chapterId t.shuqi.com,100003,书旗,bid/,/cid 想要得到: {‘100002’:‘product_name’.......}
代码如下:
def makeDict(): fileRead=open('jp_url.txt','rb') lines=fileRead.readlines() read_dict={}#定义字典 for line in lines: line_list=line.split(',')#每行按逗号分隔成列表 id=line_list[1]#取到id name=line_list[2]#取到name read_dict[id]=name#此处关键产生键值对,其中key是id read_dict.pop('product_id')#删除key为‘product_id’的键值对 return read_dict read_dict=makeDict()
2、循环写入一键对多值:
其中格式{key:[value1,value2,...]}
文本txt格式如下:
python如何编写阶乘?_Python教程
python编写阶乘的方法:首先定义一个递归函数实现求阶乘功能;然后定义一个列表,将for遍历得到的阶乘结果放到列表;最后使用【sum()】函数求和即可。
guaguashipinliaotianshi|.guagua.cn,
guaguashipinliaotianshi|iguagua.net,
guaguashipinliaotianshi|.17guagua.com,
jiuxiumeinvzhibo|.69xiu.com,
nbazhibo|.estream.cn,
youbo|yb.sxsapp.com,
其中第一列的名字有重复想要一个名字对应多个结果,代码如下:
def makehostDict(): host_dict={} f_allhost=open('xml_host.txt','rb') lines=f_allhost.readlines() for line in lines: line_list=line.split('|') name=line_list[0] host=line_list[1].strip('\n') if host is not '': if host_dict.has_key(name): host_dict.get(name).append(host)#此处为关键向字典里已经有的key(name)值后继续添加value(host) else: host_dict.setdefault(name,[]).append(host)#创建{name,[host]}value为列表的格式的字典。 return host_dict host_dict=makehostDict() print host_dict
推荐教程:《python视频教程》
以上就是python字典中如何一键多值的写入?的详细内容,更多请关注ki4网其它相关文章!
python两列字符串如何合并?_Python教程
python两列字符串合并的方法:1、使用【+】号来合并字符串,代码为【full_name = first_name+' '+ last_name】;2、创建用一个变量来存储整条语句,代码为【last_name = 'smith'】。