如何在python的嵌套列表中附加alpha值?
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ72010', 'WORD', 'FLUIDS',
'7.95']]
Expected_output:
[['72010', 'PHARMACY -IV FLUIDS', '7.95'], ['TOTAL HOSPITAL CHARGES', '6,720.92'],['PJ72010', 'WORD FLUIDS', '7.95']]
答案 0 :(得分:2)
如果创建定义单词含义的函数,则可以使用itertools.groupby()
对该函数进行分组。然后,您可以附加join()
的结果,也可以附加extend()
,具体取决于它是一组单词数。
我从您的示例中推断出,您是从没有数字的任何事物定义单词,但是您可以根据需要调整函数:
from itertools import groupby
# it's a word if it has no numerics
def word(s):
return not any(c.isnumeric() for c in s)
def groupwords(s):
sub = []
for isword, v in groupby(s, key = word):
if isword:
sub.append(" ".join(v))
else:
sub.extend(v)
return sub
res =[groupwords(l) for l in nested_list]
res
结果:
[['72010', 'PHARMACY -IV FLUIDS', '7.95'],
['TOTAL HOSPITAL CHARGES', '6,720.92'],
['PJ72010', 'WORD FLUIDS', '7.95']]
答案 1 :(得分:0)
浏览每个嵌套列表。检查该列表的每个元素。如果它是完整的alpha den,则将其附加到临时变量中。找到数字后,将临时数和数字都追加。 代码:
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ72010', 'WORD', 'FLUIDS',
'7.95']]
def isAlpha(temp):
for i in temp:
if i>='0' and i<='9':
return 0
return 1
isAlpha("abul")
anser_list=[]
for i in nested_list:
nested_list=[]
temp=""
for j in i:
if isAlpha(j)==1:
if len(temp)>0:
temp+=" "
temp+=j
else:
if len(temp)>0:
nested_list.append(temp)
temp=""
nested_list.append(j)
if len(temp)>0:
nested_list.append(temp)
anser_list.append(nested_list)
for i in anser_list:
print(i)
输出将是:
['72010', 'PHARMACY -IV FLUIDS', '7.95']
['TOTAL HOSPITAL CHARGES', '6,720.92']
['PJ72010', 'WORD FLUIDS', '7.95']