【发布时间】:2014-01-24 23:16:45
【问题描述】:
我是 python 新手,我需要一些帮助。
TASK : 给定一个列表 --> words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
我需要比较列表中每个字符串的第一个和最后一个元素, 如果字符串中的第一个和最后一个元素相同,则增加计数。
给定列表是:
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
请告诉我,我将如何比较 no 的第一个和最后一个元素。列表中的字符串。
提前致谢。
【问题讨论】:
-
对列表的迭代返回其元素而不是索引,因此会出现错误。
-
你的 Python 单线器可以做你想做的事情(但不解决或解释错误)看起来像:
c = sum([1 if w[0] == w[-1] else 0 for w in words])。但这对您没有真正的帮助,除非您开始掌握列表理解的窍门(甚至更短:c = sum([int(w[0] == w[-1]) for w in words]))。 -
@Evert 你可以放弃
int电话和[]以及.. ;-) -
@AshwiniChaudhary 嗯,我不喜欢这样对布尔值求和,但我想隐式转换在这里有效。我让它站着,否则你的评论将没有意义;-)。