Im new to python and i need some help with this.
TASK : given a list --> words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
i need to compare the first and the last element of each string in the list,
if the first and the last element in the string is the same , then increment the count.
Given list is :
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
If i try manually, i can iterate over each element of the strings in the list.
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
w1 = words[0]
print w1
aba
for i in w1:
print i
a
b
a
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
1
But, When i try to iterate over all the elements of all the strings in the list , using a FOR loop.
i get an error.
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
w1 = words[i]
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
ERROR:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str
please let me know, how would i achieve comparing the first and the last element of a no. strings in the list.
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…