[英]Python how to extract all list elements if they start with the same character set
[英]python list elements start with and end with same character
python的新手和初学者,做了一个小任务
假设您有一个名为sample的字符串列表。
编写一个遍历该列表的Python循环,并计算字符串长度为2或更大且字符串的第一个和最后一个字符相同的字符串数。
在以下三个版本的列表样本中测试您的代码:
samples = ['aba', 'xyz', 'aa', 'x', 'bbb']<br/>
samples = ['', 'x', 'xy', 'xyx', 'xx']<br/>
samples = ['aaa', 'be', 'abc', 'hello']
我尝试的方法不起作用,对我没有任何回报:
samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
if ( len(elem) >=2 and str.startswith('"') and str.endswith('"')):
print(elem)
引号不是字符串的一部分。 他们不会适合您。 相反,您想要一个最内在的比较,例如
elem.endswith(elem[0])
请注意, str是文档中所说的“将字符串放在此处”的方式。 到目前为止,让我们更新程序:
samples=['aba', 'xyz','aa', 'x', 'bbb']
for elem in samples:
if (len(elem) >=2 and elem.endswith(elem[0])):
print(elem)
输出:
aba
aa
bbb
这是一个答案,希望对您有所帮助:
results = [x for x in samples if len(x)>=2 and x[0]==x[-1]]
基本上结果是一个新列表,该列表是通过过滤具有2个条件的样本创建的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.