📜  Python程序将带有分隔符的字符串列表转换为元组列表

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

Python程序将带有分隔符的字符串列表转换为元组列表

给定一个包含带有特定分隔符的字符串的列表。任务是删除分隔符并将字符串转换为元组列表。

例子:

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

在这种情况下,首先,使用 split() 以 K 作为参数分割每个字符串,然后使用列表理解将其扩展到所有字符串。

Python3
# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using list comprehension + split()
  
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = "-"
  
# conversion using split and list comprehension
# int() is used for conversion
res = [tuple(int(ele) for ele in sub.split(K)) for sub in test_list]
  
# printing result
print("The converted tuple list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using map() + split() + list comprehension
  
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = "-"
  
# extension logic using map()
# int() is used for conversion
res = [tuple(map(int, sub.split(K))) for sub in test_list]
  
# printing result
print("The converted tuple list : " + str(res))


输出
The original list is : ['1-2', '3-4-8-9', '4-10-4']
The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

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

这里使用map()完成积分扩展逻辑的扩展任务,然后使用列表推导来执行构建列表的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using map() + split() + list comprehension
  
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = "-"
  
# extension logic using map()
# int() is used for conversion
res = [tuple(map(int, sub.split(K))) for sub in test_list]
  
# printing result
print("The converted tuple list : " + str(res))
输出
The original list is : ['1-2', '3-4-8-9', '4-10-4']
The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]