拆分字符串并将其转换为字典的Python程序
给定一个分隔符(在代码中表示为delim )分隔的字符串,以字典的形式对拆分进行排序。
例子 :
Input : test_str = ‘gfg*is*best*for*geeks’, delim = “*”
Output : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}
Input : test_str = ‘gfg*is*best’, delim = “*”
Output : {0: ‘gfg’, 1: ‘is’, 2: ‘best’}
方法 1:使用 split() + 循环
这是可以执行此任务的粗暴方式。在这种情况下,使用 split() 将拆分部分存储在临时列表中,然后从临时列表创建新字典。
Python3
# Using split() + loop
# initializing string
test_str = 'gfg_is_best_for_geeks'
# printing original string
print("The original string is : "
+ str(test_str))
# initializing delim
delim = "_"
# splitting using split()
temp = test_str.split(delim)
res = dict()
# using loop to reform dictionary with splits
for idx, ele in enumerate(temp):
res[idx] = ele
# printing result
print("Dictionary after splits ordering : "
+ str(res))
Python3
# Using dictionary comprehesion + split() + enumerate()
# initializing string
test_str = 'gfg_is_best_for_geeks'
# printing original string
print("The original string is : "
+ str(test_str))
# initializing delim
delim = "_"
# using one liner to rearrange dictionary
res = {idx: ele for idx, ele in
enumerate(test_str.split(delim))}
# printing result
print("Dictionary after splits ordering : "
+ str(res))
输出:
The original string is : gfg_is_best_for_geeks
Dictionary after splits ordering : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}
方法 2:使用字典理解 + split() + enumerate()
这是可以执行此任务的速记方法。在此,我们使用单行字典(字典理解)执行字典重建任务,并使用 enumerate() 帮助排序。
蟒蛇3
# Using dictionary comprehesion + split() + enumerate()
# initializing string
test_str = 'gfg_is_best_for_geeks'
# printing original string
print("The original string is : "
+ str(test_str))
# initializing delim
delim = "_"
# using one liner to rearrange dictionary
res = {idx: ele for idx, ele in
enumerate(test_str.split(delim))}
# printing result
print("Dictionary after splits ordering : "
+ str(res))
输出:
The original string is : gfg_is_best_for_geeks
Dictionary after splits ordering : {0: ‘gfg’, 1: ‘is’, 2: ‘best’, 3: ‘for’, 4: ‘geeks’}