如何在python的嵌套列表中附加alpha值?

2024-05-16 02:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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']]

Tags: alpha列表outputlistwordtotalnestedexpected
2条回答

浏览每个嵌套列表。检查列表中的每个元素。如果是完整的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']

如果您创建的函数定义了word的含义,那么可以使用^{}按此函数分组。然后您可以附加join()ed结果或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']]

相关问题 更多 >