📜  Python|合并连续的数字字符串

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

Python|合并连续的数字字符串

有时,在处理数据时,我们可能会遇到需要执行数字合并的问题。这是一个更简单的问题。但是,一旦我们需要对某些元素(例如过于连续的数字)进行合并,它就会变得复杂。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + groupby() + isdigit()
上述功能的组合可用于执行此任务。在此,我们首先将所有数字连续分组,然后执行连接。

Python3
# Python3 code to demonstrate
# Merge Consecutive digits Strings
# using list comprehension + groupby() + isdigit()
from itertools import groupby
 
# Initializing list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Merge Consecutive digits Strings
# using list comprehension + groupby() + isdigit()
res = [sub for i, j in groupby(test_list, str.isdigit) for sub in ([''.join(j)] if i else j)]
 
# printing result
print ("List after digit merge : " + str(res))


Python3
# Python3 code to demonstrate
# Merge Consecutive digits Strings
# using regex() + join()
import re
 
# Initializing list
test_list = ['g', '1', '2', 'i', '5', 'b', '6', '7']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Merge Consecutive digits Strings
# using regex() + join()
res = re.findall('\d+|.', ''.join(test_list))
 
# printing result
print ("List after digit merge : " + str(res))


输出 :
The original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge : ['gfg', '12', 'is', '5', 'best', '67']


方法#2:使用正则表达式 + join()
上述功能的组合也可以用来处理这个问题。在此,我们使用 regex函数查找数字并使用 join() 执行合并。仅适用于单个字符。

Python3

# Python3 code to demonstrate
# Merge Consecutive digits Strings
# using regex() + join()
import re
 
# Initializing list
test_list = ['g', '1', '2', 'i', '5', 'b', '6', '7']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Merge Consecutive digits Strings
# using regex() + join()
res = re.findall('\d+|.', ''.join(test_list))
 
# printing result
print ("List after digit merge : " + str(res))
输出 :
The original list is : ['g', '1', '2', 'i', '5', 'b', '6', '7']
List after digit merge : ['g', '12', 'i', '5', 'b', '67']