如何在python中连接iterable(字符串连接)?
我看过其他有类似问题的帖子 这是我的代码:如何在python中连接iterable(字符串连接)?,python,python-3.x,Python,Python 3.x,我看过其他有类似问题的帖子 这是我的代码: def fit_replace(text): text = np.array(text) text = ' '.join(text) return text df['REPLACE'] = df['ISI'].apply(fit_replace) df.head(5) 这是文本中的列表: [['ini', 'juga', 'saya', 'sambil', 'disambi', 'kerja', 'masih', 'bela
def fit_replace(text):
text = np.array(text)
text = ' '.join(text)
return text
df['REPLACE'] = df['ISI'].apply(fit_replace)
df.head(5)
这是文本中的列表:
[['ini', 'juga', 'saya', 'sambil', 'disambi', 'kerja', 'masih', 'belajar',...
错误:
<ipython-input-101-15e80ecfee7e> in fit_replace(text)
1 def fit_replace(text):
2 text = np.array(text)
----> 3 text = ' '.join(text)
4 return text
5
TypeError: can only join an iterable
安装中的替换(文本)
1 def安装和更换(文本):
2 text=np.array(text)
---->3文本=“”。连接(文本)
4返回文本
5.
TypeError:只能加入一个iterable
您需要先将文本
转换为iterable
例如:
加入(列表(文本))
您应该使用:
df['REPLACE'] = df['ISI'].apply(''.join)
将为您省去定义单独函数、转换广告应用的麻烦。这毫无意义<代码>列表本身需要一个iterable来构造它。
str.join
实现的第一步是将任何尚未成为tuple
或list
的输入转换为list
,方法与list
构造函数相同。从定义上讲,如果''.join(list(text))
有效,那么'.join(text)
也有效。如果上述方法有效,更简单的解决方案是df['REPLACE']=df['ISI'].apply('.join)
。您不需要一个lambda
接受一个参数并将其传递给另一个接受一个参数的函数,而另一个函数已经接受一个参数并完全按照您的要求执行。同样,OP的原始代码应该是df['REPLACE']=df['ISI'];如果您有一个one arg函数可以执行您想要的操作,请停止无缘无故地将其包装到另一个lambda
中。正确!它确实起到了作用。我还要补充一点