use*_*141 18 python string list
我是python的新手,我需要一些帮助.
任务:给出一个清单 - > words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
我需要比较列表中每个字符串的第一个和最后一个元素,如果字符串中的第一个和最后一个元素相同,则递增计数.
给出的列表是:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
Run Code Online (Sandbox Code Playgroud)
如果我手动尝试,我可以迭代列表中字符串的每个元素.
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
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试迭代列表中所有字符串的所有元素时,使用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
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)
请告诉我,如何比较一个号码的第一个和最后一个元素.列表中的字符串.
提前致谢.
Ste*_*ima 36
尝试:
for word in words:
if word[0] == word[-1]:
c += 1
print c
Run Code Online (Sandbox Code Playgroud)
for word in words返回项目words,而不是索引.如果您需要某个时间的索引,请尝试使用enumerate:
for idx, word in enumerate(words):
print idx, word
Run Code Online (Sandbox Code Playgroud)
会输出
0, 'aba'
1, 'xyz'
etc.
Run Code Online (Sandbox Code Playgroud)
将-1在word[-1]上面说:"最后一个元素"的Python的方式.word[-2]会给你第二个元素,依此类推.
您也可以使用生成器来实现此目的.
c = sum(1 for word in words if word[0] == word[-1])
Run Code Online (Sandbox Code Playgroud)