【问题标题】:Looping over string elements in Python list and making substitutions循环遍历 Python 列表中的字符串元素并进行替换
【发布时间】:2014-05-01 18:06:46
【问题描述】:

我有一个如下所示的列表:

>>> lst = ['yaktub', 'naktub', 'taktub']

我知道如何遍历列表中的项目。但我想遍历列表中每个元素的字符并进行替换。我将在下面提供一个伪代码:

for item in lst: 
      for char in lst[item]:
          if lst[item][0] in 'ynt':


                lst[item][0] = char
          elif lst[item][1] in 'a':
                  lst[item][1] = 'a'
          elif lst[item][2] in 'k':
                lst[item][2] = 'f'
       newlst.append(item)
return newlest

等等。如果您能指导我如何使用索引分配而不是切片,我将不胜感激。

【问题讨论】:

  • 我不太明白你的问题是什么......
  • 请解释一下这背后的逻辑...

标签: python string list substitution


【解决方案1】:

您应该为此使用translate,如:

lst = ['yaktub', 'naktub', 'taktub']
for word in lst:
    print(word.translate(str.maketrans("yntak", "yntaf")))

哪些输出:

yaftub
naftub
taftub

请注意,第一个列表是您要替换的字符,第二个是您要出现在新字符串中的字符。

【讨论】:

    【解决方案2】:

    在python中,字符串只是一个列表 '字符串' == ['s','t','r','i','n','g'] 那么

    lst = ['yaktub', 'naktub', 'taktub']
    newlst = []
    for item in lst: 
          for char in item:
              if char in 'ynt':
                  #your operation here
              elif char in 'a':
                  #other code here
           newlst.append(item)
    return newest
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      因为我不确定是否需要,但最好尝试一下

      def convert_word(word):
          ....your code here and add return statement
      
      map(convert_word,list_to_convert)
      

      你去!

      请下次尝试更好地解释需求

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 2014-09-19
        • 1970-01-01
        • 2019-10-31
        • 2011-05-06
        • 1970-01-01
        相关资源
        最近更新 更多