【问题标题】:Removing a character from a string in a list of lists从列表列表中的字符串中删除字符
【发布时间】:2015-10-25 23:48:39
【问题描述】:

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

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

【问题讨论】:

  • 阅读文档。 replace 并没有按照你的想法去做。

标签: python string list replace


【解决方案1】:

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]

【讨论】:

  • 谢谢阿南德,这就像一个魅力。 j, item, enumerate 语法对于像我这样的新手来说很微妙,而且我敢肯定在以后的路上会很有用。列表推导式是 Python 的一大优点,因此感谢您提供额外的解决方案!
  • 很高兴能为您提供帮助。如果答案对你有帮助。我想建议您接受答案(通过单击答案左侧的勾号),这将对社区有所帮助
  • 完成。感谢您填写社区协议。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      y = []
      for lst in testList:
          for a in lst:
              z = a.replace('*','')
              y.append(z)
      testList = []
      testList.append(y)
      print testList
      

      【讨论】:

      • 解释一下总是有帮助的
      【解决方案5】:

      在您的代码中,您只替换了虚拟变量中的*,而不影响列表条目。使用lstrip 只会从字符串的左侧取*

      for x in xrange(len(testList)):
          testList[x] = testList[x].lstrip('*')
      

      【讨论】:

        猜你喜欢
        • 2020-12-14
        • 2021-06-24
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        相关资源
        最近更新 更多