Python程序来加入同等层次的字符串
给定具有多个层次结构的字符串列表,任务是编写一个Python程序来连接具有相同层次结构的字符串。
已知维度更改之前同一维度中的元素位于同一层次结构中。
Input : test_list = [“gfg “, ” best “, [” for “, ” all “], ” all “, [” CS ” , ” geeks “]]
Output : [‘gfg best ‘, [‘ for all ‘], ‘ all ‘, [‘ CS geeks ‘]]
Explanation : Strings at similar hierarchy as joined.
Input : test_list = [“gfg “, ” best “, [” for “, ” all “], [” CS ” , ” geeks “]]
Output : [‘gfg best ‘, [‘ for all ‘], [‘ CS geeks ‘]]
Explanation : Strings at similar hierarchy as joined.
方法 1:使用 type()、循环、递归和 join()
在此,使用 type() 检查列表元素是否为字符串,如果找到,则使用该层次结构的 join 执行加入任务。如果发现元素是列表,则为下一级层次结构的类似逻辑重复内部列表。
例子:
Python3
def hierjoin(test_list):
res = []
temp = []
val = None
for sub in test_list:
# if string then appended
if type(sub) == str:
temp.append(sub)
# if list, the string is joined for hierarchy
# recurred for inner list
else:
res.append(''.join(temp))
temp = []
val = hierjoin(sub)
res.append(val)
if temp != []:
res.append(''.join(temp))
return res
# initializing list
test_list = ["gfg ", " best ", [" for ", " all "],
" all ", [" CS ", " geeks "]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursion
res = hierjoin(test_list)
# printing result
print("The joined strings : " + str(res))
Python3
from itertools import groupby
def hierjoin(test_list):
# groups are formed for similar hierarchy using groupby
return [idx for x, y in groupby(test_list, key=str.__instancecheck__)
for idx in ([''.join(y)] if x else map(hierjoin, y))]
# initializing list
test_list = ["gfg ", " best ", [" for ", " all "],
" all ", [" CS ", " geeks "]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursion
res = hierjoin(test_list)
# printing result
print("The joined strings : " + str(res))
输出:
The original list is : [‘gfg ‘, ‘ best ‘, [‘ for ‘, ‘ all ‘], ‘ all ‘, [‘ CS ‘, ‘ geeks ‘]]
The joined strings : [‘gfg best ‘, [‘ for all ‘], ‘ all ‘, [‘ CS geeks ‘]]
方法 2:使用 join()、map()、递归和 groupby()
在这个 equihierarchy 中,组是使用 groupby() 形成的。然后 map() 用于调用列表字符串 的内部层次结构的递归函数。
例子:
蟒蛇3
from itertools import groupby
def hierjoin(test_list):
# groups are formed for similar hierarchy using groupby
return [idx for x, y in groupby(test_list, key=str.__instancecheck__)
for idx in ([''.join(y)] if x else map(hierjoin, y))]
# initializing list
test_list = ["gfg ", " best ", [" for ", " all "],
" all ", [" CS ", " geeks "]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursion
res = hierjoin(test_list)
# printing result
print("The joined strings : " + str(res))
输出:
The original list is : [‘gfg ‘, ‘ best ‘, [‘ for ‘, ‘ all ‘], ‘ all ‘, [‘ CS ‘, ‘ geeks ‘]]
The joined strings : [‘gfg best ‘, [‘ for all ‘], ‘ all ‘, [‘ CS geeks ‘]]