python - 为什么这个函数没有正确调用?
问题描述
def func_list(l):
t=list()
z=list(l)
for i in range(0,len(z)-1):
if(z[i]==' '):continue
a=z[i].split(':')
if(a[0]==''): continue
for j in range(i+1,len(z)-1):
b=z[j].split(':')
if(b[0]==' '): break
if a[0]==b[0]:
z[i]=z[i]+' '+b[1]
z[j]=' '
else:
t.append(z[i])
break
return t
df_head['Message']=df_head['Message'].apply(func_list)
调用此函数时出现此错误
IndexError Traceback (most recent call last)
<ipython-input-41-d8f85a0144bf> in <module>
----> 1 df_head['Message']=df_head['Message'].apply(func_list)
~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
3192 else:
3193 values = self.astype(object).values
-> 3194 mapped = lib.map_infer(values, f, convert=convert_dtype)
3195
3196 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-40-00055f2d4f69> in func_list(l)
14 if a[0]==b[0]:
15
---> 16 z[i]=z[i]+' '+b[1]
17 z[j]=' '
18 else:
IndexError: list index out of range
解决方案
添加检查 b 的长度,然后使用 b[1] 进行下一个处理,例如
def func_list(l):
t=list()
z=list(l)
for i in range(0,len(z)-1):
if(z[i]==' '):continue
a=z[i].split(':')
if(a[0]==''): continue
for j in range(i+1,len(z)-1):
b=z[j].split(':')
if(b[0]==' '): break
if a[0]==b[0] and len(b)>1:
z[i]=z[i]+' '+b[1]
z[j]=' '
else:
t.append(z[i])
break
return t
推荐阅读
- r - 仅保留第一个值(对于特定值),但为具有相同值的所有其他行创建零
- c# - LiveCharts 在更改轴(MinValue 和 MaxValue)或添加新数据时重新渲染整个绘图
- go - 使用反射获取结构标记 - 错误:类型 reflect.Value 没有字段或方法标记
- python - 将元组中的元素相乘
- python - Matplotlib 保存空白图
- python - 使用 rsplit 从字符串末尾删除某些字母的单行器?
- regex - NLTK 正则表达式解析器的输出已更改。无法解析动词后跟名词之类的短语
- reactjs - 动态链接在 react-app 的构建中不起作用
- python - 如何在python中对字符串进行子串化?
- excel - VBA:将子程序包含在条件中