python 练习题
1.【编码实现】有如下数组,需要将每个字符串中排列在任意 x 前⾯的所有 y 替换为 0 ,需要计算出
每个字符串需要被替换的 y 的个数,请使⽤⼀⻔您熟悉的编程语⾔实现。
[\'xxyyxyyyyyxxx\', \'yxxxx\', \'xyyyxxyx\', \'xxxx\', \'xxxyyy\']
import relist1 = [\'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)
打印结果:
以上是 python 练习题 的全部内容, 来源链接: utcz.com/z/389416.html