📜  Python - 连续对逗号删除

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

Python - 连续对逗号删除

有时,在处理列表时,我们可能会遇到需要将两个列表中的元素配对的问题。在这种情况下,我们可以有对,我们发现有逗号打印在元组中,我们希望通常避免它。让我们讨论可以执行此任务的某些方式。

方法 #1:使用zip() + list comprehension + replace()
上述功能的组合可用于执行此任务。在此,我们使用 zip() 加入列表,并使用 replace() 执行删除逗号和加入的任务。

# Python3 code to demonstrate 
# Consecutive Pairs Duplication Removal
# using list comprehension + zip() + replace()
  
# Initializing lists
test_list1 = [1, 2, 3, 4, 5]
test_list2 = [2, 3, 4, 5, 6]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Consecutive Pairs Duplication Removal
# using list comprehension + zip() + replace()
res = str(list(zip(test_list1, test_list2))).replace('), (', ') (')
          
# printing result 
print ("The combined list after consecutive comma removal : " + str(res))
输出 :
The original list 1 is : [1, 2, 3, 4, 5]
The original list 2 is : [2, 3, 4, 5, 6]
The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]

方法 #2:使用map() + list comprehension + zip()
这是可以执行此任务的另一种方式。在此我们执行使用 replace() 和 map() 执行的任务。

# Python3 code to demonstrate 
# Consecutive Pairs Duplication Removal
# using list comprehension + zip() + map()
  
# Initializing lists
test_list1 = [1, 2, 3, 4, 5]
test_list2 = [2, 3, 4, 5, 6]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Consecutive Pairs Duplication Removal
# using list comprehension + zip() + map()
res = "[" + " ".join(map(str, zip(test_list1, test_list2))) + "]"
          
# printing result 
print ("The combined list after consecutive comma removal : " + str(res))
输出 :
The original list 1 is : [1, 2, 3, 4, 5]
The original list 2 is : [2, 3, 4, 5, 6]
The combined list after consecutive comma removal : [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]