python 练习题
2021-04-03 01:25
标签:方法 代码 练习题 打印 数组 port imp str sea 打印结果: 2.【编码实现】请使???您熟悉的编程语?实现如下数据结构转换 实现代码: 打印结果: python 练习题 标签:方法 代码 练习题 打印 数组 port imp str sea 原文地址:https://www.cnblogs.com/muzii/p/13471438.htmlimport 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)
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)