📜  Python|合并相邻的数字字符

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

Python|合并相邻的数字字符

有时,不止一种类型的数据可能会出现在Python列表中,有时它会被不希望地标记化,因此我们需要连接已标记化的数字并保持字母表原样。让我们讨论一些可以实现此任务的方法。

方法#1:使用列表理解+ "*" operator
可以使用列表推导来执行此任务,首先连接数字,然后连接单词,然后仅分隔单词,同时连接以形成结果字符串。

# Python3 code to demonstrate
# Merge adjacent Digit characters
# list comprehension + "*" operator
  
# initializing list 
test_list = ['Geeks', 'for', 'Geeks', '2', '5']
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + "*" operator
# Merge adjacent Digit characters
res = [''.join([i for i in test_list if not i.isalpha()]), *[j for j in test_list if j.isalpha()]]
  
# print result
print("The joined adjacent word list(ignoring alphabets) : " + str(res))
输出 :
The original list : ['Geeks', 'for', 'Geeks', '2', '5']
The joined adjacent word list(ignoring alphabets) : ['25', 'Geeks', 'for', 'Geeks']

方法#2:使用itertools.chain.from_iterable() + groupby() + join()
也可以使用 groupby函数执行此任务,该函数将字母组合在一起,然后 from_iterables函数将列表和字符连接在一起,由 join函数连接。

# Python3 code to demonstrate
# Merge adjacent Digit characters
# itertools.chain.from_iterable() + groupby() + join()
from itertools import chain, groupby
  
# initializing list 
test_list = ['Geeks', 'for', 'Geeks', '2', '5']
  
# printing original list
print("The original list : " + str(test_list))
  
# using itertools.chain.from_iterable() + groupby() + join()
# Merge adjacent Digit characters
num_group = groupby(test_list, key = str.isdigit)
both_group = [[''.join(i)] if j else list(i) for j, i in num_group]
res = list(chain.from_iterable(both_group))
  
# print result
print("The joined adjacent word list(ignoring alphabets) : " + str(res))
输出 :
The original list : ['Geeks', 'for', 'Geeks', '2', '5']
The joined adjacent word list(ignoring alphabets) : ['25', 'Geeks', 'for', 'Geeks']