给定一个列表:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
我需要比较列表中每个字符串的第一个和最后一个元素。如果字符串中的第一个和最后一个元素相同,则增加计数。
如果我手动尝试,我可以遍历列表中字符串的每个元素:
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
循环遍历列表中所有字符串的所有元素时,出现错误。
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
我将如何比较字符串列表的第一个和最后一个元素?
原文由 user3168141 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试:
for word in words
返回 ---words
--- 的项目,而不是索引。如果您有时需要索引,请尝试使用enumerate
:会输出
-1
中的word[-1]
是Python表达“最后一个元素”的方式。word[-2]
会给你倒数第二个元素,依此类推。您也可以使用生成器来实现此目的。