How to iterate over each string in a list of strings and operate on it's elements

前端 未结 8 1927
别跟我提以往
别跟我提以往 2020-12-25 13:00

Im new to python and i need some help with this.

TASK : given a list --> words = [\'aba\', \'xyz\', \'xgx\', \'dssd\', \'sdjh\']

i need to com

相关标签:
8条回答
  • 2020-12-25 13:19

    The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:

    words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
    count = 0  
    for i in words:  
         if i[0]==i[-1]:
            count = count + 1  
    print(count)  
    

    Output:

    $python main.py
    3
    
    0 讨论(0)
  • 2020-12-25 13:27

    Try:

    for word in words:
        if word[0] == word[-1]:
            c += 1
        print c
    

    for word in words returns the items of words, not the index. If you need the index sometime, try using enumerate:

    for idx, word in enumerate(words):
        print idx, word
    

    would output

    0, 'aba'
    1, 'xyz'
    etc.
    

    The -1 in word[-1] above is Python's way of saying "the last element". word[-2] would give you the second last element, and so on.

    You can also use a generator to achieve this.

    c = sum(1 for word in words if word[0] == word[-1])
    
    0 讨论(0)
提交回复
热议问题