ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python 练习题

2020-08-10 18:33:08  阅读:226  来源: 互联网

标签:练习题 dict1 name python list list2 type id


1.【编码实现】有如下数组,需要将每个字符串中排列在任意 x 前⾯的所有 y 替换为 0 ,需要计算出 每个字符串需要被替换的 y 的个数,请使⽤⼀⻔您熟悉的编程语⾔实现。 ['xxyyxyyyyyxxx', 'yxxxx', 'xyyyxxyx', 'xxxx', 'xxxyyy']
import re
list1 = ['xxyyxyyyyyxxx', 'yxxxx', 'xyyyxxyx', 'xxxx', 'xxxyyy','yxxxyyy']
list2 = []
sum=0
for str1 in list1:
    
    while True:
        searchObj = re.search('(y+)x',str1)
        if searchObj:
            index=searchObj.span()
            sum = sum + index[1]-index[0]-1
            str1=str1.replace(str1[index[0]:index[1]-1],(index[1]-1-index[0])*'0',1)
        else:
            list2.append(str1)
            break
print('sum(y):',sum)
print('replace list:',list2)

打印结果:

 

 2.【编码实现】请使⽤⼀⻔您熟悉的编程语⾔实现如下数据结构转换

list = [
 { id: 1, type: 'human', name: '⿅晗' },
 { id: 2, type: 'robot', name: '伊娃' },
 { id: 3, type: 'animal', name: '⾖⾖' },
 { id: 4, type: 'human', name: '蔡徐坤' },
 { id: 5, type: 'robot', name: '夏娃' }
];
转换为:
{
 'human': [{ id: 1, name: '⿅晗' },{ id: 4, name: '蔡徐坤' }],
 'robot': [{ id: 2, name: '伊娃' },{ id: 5, name: '夏娃' }],
 'animal': [{ id: 3, name: '⾖⾖' }],
}

实现代码:

list = [
    { 'id': 1, 'type': 'human', 'name': '⿅晗' },
    { 'id': 2, 'type': 'robot', 'name': '伊娃' },
    { 'id': 3, 'type': 'animal', 'name': '⾖⾖' },
    { 'id': 4, 'type': 'human', 'name': '蔡徐坤' },
    { 'id': 5, 'type': 'robot', 'name': '夏娃' }
]

dict1 = {}
方法1:
for i in range(0,len(list)):
    s = list[i].pop('type')
    if s in dict1.keys():
        dict1[s].append(list[i])
    else:
        list2 = []
        list2.append(list[i])
        dict1[s]=list2    
print(dict1)
方法2:
for item in list:
    if item['type'] in dict1.keys():
        s=item.pop('type')
        dict1[s].append(item)
        #print('dict1',dict1)
    else:   
        list2=[]
        s=item.pop('type')     
        list2.append(item)
        # print('list2',list2)
        dict1[s] = list2
        # print('dict1',dict1)
prin(dict1)

打印结果:

 

 

标签:练习题,dict1,name,python,list,list2,type,id
来源: https://www.cnblogs.com/muzii/p/13471438.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有