📌  相关文章
📜  Python – 将分隔符分隔的混合字符串转换为有效列表

📅  最后修改于: 2022-05-13 01:54:29.384000             🧑  作者: Mango

Python – 将分隔符分隔的混合字符串转换为有效列表

给定一个带有元素和分隔符的字符串,在分隔符上拆分元素以提取元素(包括容器)。

方法 #1:使用循环 + eval() + split()

这是可以完成此任务的一种方式。在这种情况下,使用 split() 完成分离,而 eval() 完成了将数据类型评估为容器或更简单元素的重要任务。

Python3
# Python3 code to demonstrate working of
# Convert delimiter separated Mixed String to valid List
# Using loop + split() + eval()
 
# initializing string
test_str = "6# 2# 9#[3, 5, 6]#(7, 8)# 8# 4# 10"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "#"
 
# splitting using split()
temp = test_str.split(delim)
res = []
 
# using loop + eval() to convert to
# required result
for ele in temp:
  res.append(eval(ele))
 
# printing result
print("List after conversion : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert delimiter separated Mixed String to valid List
# Using eval() + split() + list comprehension
 
# initializing string
test_str = "6# 2# 9#[3, 5, 6]#(7, 8)# 8# 4# 10"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "#"
 
# encapsulating entire result in list comprehension
res = [eval(ele) for ele in test_str.split(delim)]
 
# printing result
print("List after conversion : " + str(res))


输出
The original string is : 6#2#9#[3, 5, 6]#(7, 8)#8#4#10
List after conversion : [6, 2, 9, [3, 5, 6], (7, 8), 8, 4, 10]

方法 #2:使用 eval() + split() + 列表理解

这是可以执行此任务的另一种方式。在此,我们执行与上述方法类似的任务。唯一的区别是整个逻辑使用列表理解封装为一个衬垫。

Python3

# Python3 code to demonstrate working of
# Convert delimiter separated Mixed String to valid List
# Using eval() + split() + list comprehension
 
# initializing string
test_str = "6# 2# 9#[3, 5, 6]#(7, 8)# 8# 4# 10"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing delim
delim = "#"
 
# encapsulating entire result in list comprehension
res = [eval(ele) for ele in test_str.split(delim)]
 
# printing result
print("List after conversion : " + str(res))
输出
The original string is : 6#2#9#[3, 5, 6]#(7, 8)#8#4#10
List after conversion : [6, 2, 9, [3, 5, 6], (7, 8), 8, 4, 10]