在for循环中列出值赋值

时间:2017-01-23 20:00:04

标签: list python-3.x for-loop

当我在此代码中出现以下错误时,我该怎么办?

(function() {


  var helloComponenet = ng.core.Component({
      selector: 'hello-comp',
      template: '<h2> Hello Component </h2>'
    })
    .Class({
      constructor: function() {}
    });

  var myApp = ng.core.Component({
      selector: 'my-app',
      template: '<h1> Does Something </h1> <br>' + '<hello-comp></hello-comp>'
    })
    .Class({
      constructor: function() {},
      directives: [helloComponenet]
    });


  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(myApp);
  });



}());
  

def reverse_word(word): index = len(word) new_word = [] for i in range(index - 1, -1, -1): new_word.append(word[i]) return ''.join(new_word) def reverse_sentence(sentence): l = sentence.split() for i in l: l[i] = reverse_word(i) l = ' '.join(l) print(l) a = "Hello !Nhoj Want to have lunch?" reverse_sentence(a)

我可以写什么而不是这一行:

TypeError: list indices must be integers or slices, not str.

1 个答案:

答案 0 :(得分:0)

...此行:l[i] = reverse_word(i)会引发错误,因为i是一个字符串(word),但在l[i]i 必须是一个索引

你可能想做这样的事情:

words = sentence.plit()
new_sentence = []
for i,word in enumerate(words): #or just for word in words, you don't need the index
    new_sentence.append(reverse_word(word))

然后在返回时间加入return ' '.join(new_sentence)

此实现遵循您的逻辑,但使用字符串而不是列表。

def reverse_word(word): 
    new_word = ''
    for i in range(len(word) - 1, -1, -1):
        new_word += word[i]
    return new_word

def reverse_sentence(sentence):
    r = ''
    for word in sentence.split():
        r += reverse_word(word) + ' ' 
    return r[:-1]

>>> a = "Hello !Nhoj Want to have lunch?"   
>>> reverse_sentence(a)
>>> 'olleH johN! tnaW ot evah ?hcnul'