如何遍历字符串列表中的每个字符串并对其元素进行操作 [英] How to iterate over each string in a list of strings and operate on it's elements

查看:1693
本文介绍了如何遍历字符串列表中的每个字符串并对其元素进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我需要一些帮助.

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

任务:给出一个列表-> words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

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.

列表为:

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

但是,当我尝试使用FOR循环遍历列表中所有字符串的所有元素时.

But, When i try to iterate over all the elements of all the strings in the list , using a FOR loop.

我得到一个错误.

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

错误:

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.

谢谢.

推荐答案

尝试:

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

for word in words返回words的项目,而不是索引.如果您有时需要索引,请尝试使用enumerate:

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

将输出

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

上面word[-1]中的-1是Python所说的最后一个元素"的方式. word[-2]将给您倒数第二个元素,依此类推.

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

这篇关于如何遍历字符串列表中的每个字符串并对其元素进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆