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

2024-04-29 21:24:25 发布

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

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

[['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,它会打印正确的项目。


Tags: 数据字符串inforageifversionitem
3条回答

您必须创建一个新的list(如下所示)或访问旧的索引。

new_list = [[item.replace('*','') if item[0]=='*' else item for item in l] for l in old_list]

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

示例-

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]

您可以尝试使用枚举,以便在需要更改列表元素的索引时访问该索引:

 for lst in testList:
      for i, item in enumerate(lst):
          if item.startswith('*'):
               lst[i] = item[1:] # Or lst[i] = item.replace('*', '') for more

相关问题 更多 >