我正在编写一个函数,该函数将2个字符串作为输入,并将字典的一部分移到另一个。
, CASE WHEN [ordernumber] Is Not Null THEN
SUBSTRING([ordernumber],CHARINDEX('-', [ordernumber], CHARINDEX('-', [ordernumber]) + 1) -0,
LEN([ordernumber]) - CHARINDEX('/', [ordernumber], CHARINDEX('/', [ordernumber]) + 1) -
CHARINDEX('-', REVERSE(rtrim([ordernumber])))) ELSE '' END AS PulledString
我的初始词典是这样的。
class BeachResortServiceApplicationTests {
private PersonDataAccessService service;
@BeforeEach
void init() {
service = new PersonDataAccessService();
}
@Test
void test1() {
System.out.println("Test1");
UUID id = UUID.randomUUID();
Person bob = new Person(id, "Bob");
service.insertPerson(bob);
assert(service.getPersonById(id).equals(bob));
}
@Test
void test2() {
System.out.println("Test2");
System.out.println(service.getAllPersons());
//this assertion fails because service still has Bob in it but service should have been cleared
//according to the @BeforeEach method.
assertThat(service.getAllPersons()).hasSize(0);
}
}
我想将字典的一个小节或小节移到另一小节。这些部分由路径的每个键(以“ /”分隔)表示。例如,我函数的输入为:
def move(item_to_move, destination):
# do something....
输出为:
directories = {
'beers': {
'ipa': {
'stone': {}
}
},
'wines': {
'red': {
'cabernet': {}
}
},
'other' : {}
}
注意:我假设items_to_move的所有输入路径都是有效的。
答案 0 :(得分:1)
找到起点的父字典和目标字典,然后使用起点的键和值(从起点的父目录中删除)更新目标字典:
def move(tree,originPath,targetPath):
originKey = None
for originName in originPath.split("/"):
originParent = originParent[originKey] if originKey else tree
originKey = originName
targetDict = tree
for targetName in targetPath.split("/"):
targetDict = targetDict[targetName]
targetDict.update({originKey:originParent.pop(originKey)})
输出:
directories = {
'beers': {
'ipa': {
'stone': {}
}
},
'wines': {
'red': {
'cabernet': {}
}
},
'other' : {}
}
move(directories,'beers/ipa','other')
print(directories)
{ 'beers': {},
'wines': { 'red': {'cabernet': {}} },
'other': { 'ipa': {'stone': {}} }
}