gpt4 book ai didi

python - 从列表列表中的字符串中删除字符

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:44 28 4
gpt4 key购买 nike

我正在尝试格式化一些数据以进行分析。我正在尝试从所有以 one 开头的字符串中删除 '*'。这是数据的一个片段:

[['Version', 'age', 'language', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q16', 'Q17', 'Q18', 'Q19', 'Q20', 'Q21', 'Q22', 'Q23', 'Q24', 'Q25', 'Q26', 'Q27', 'Q28', 'Q29', 'Q30', 'Q31', 'Q32', 'Q33', 'Q34', 'Q35', 'Q36', 'Q37', 'Q38', 'Q39', 'Q40', 'Q41', 'Q42', 'Q43', 'Q44', 'Q45'], ['1', '18 to 40', 'English', '*distort', '*transfer', '*retain', 'constrict', '*secure', '*excite', '*cancel', '*hinder', '*overstate', 'channel', '*diminish', '*abolish', '*comprehend', '*tolerate', '*conduct', '*destroy', '*foster', 'direct', '*challenge', 'forego', '*cause', '*reduce', 'interrupt', '*enhance', '*misapply', '*exhaust', '*extinguish', '*assimilate', 'believe', 'harmonize', '*demolish', 'affirm', 'trouble', 'discuss', '*force', 'divide', '*remove', '*release', 'highlight', 'reinforce', 'stifle', '*compromise', '*experience', 'evaluate', 'replenish']]

这应该很简单,但我尝试过的都不起作用。例如:

for lst in testList:
for item in lst:
item.replace('*', '')

只是给我返回相同的字符串。我还尝试插入一个 if 语句并为字符串中的字符编制索引。我知道我可以访问字符串。例如,如果我说 if item[0] == '*': print item 它会打印正确的项目。

最佳答案

string 是不可变的,因此 item.replace('*','') 返回带有替换字符的字符串,它不会替换它们inplace(它不能,因为 string 是不可变的)。您可以枚举列表,然后将返回的字符串分配回列表 -

例子-

for lst in testList:
for j, item in enumerate(lst):
lst[j] = item.replace('*', '')

您也可以通过列表理解轻松地做到这一点 -

testList = [[item.replace('*', '') for item in lst] for lst in testList]

关于python - 从列表列表中的字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794610/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com