Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...