如何在Python中使用".endswith"对字符串列表进行操作?

3

我在Python中遇到了一个问题,需要修改给定文本文件中的文本(读模式,而非写模式)。下面是我的一部分代码:

file = open("fileName")
suffix_list:[]

for e in file:
    elements=e.split()
    result=elements.endswith("a")
    suffix_list.append(result)

然后我想要打印带有后缀的列表长度:

print(len(suffix_list))

我得到了这个错误信息:" 'list' object has no attribute 'endswith' ",我真的不确定出了什么问题,请问有人可以帮忙吗?


5
elements是一个列表。您无法检查它是否以某个字符串"结尾"。此外,suffix_list:[]不会创建空列表。 - DYZ
1
你期望的输出是什么:一个字符串的扁平列表,还是一个由多个字符串列表组成的列表(每行一个列表)? - DYZ
一个字符串的平面列表 - Charlotte
仅供他人参考:endswith() 全部小写且区分大小写。如果您看到以下错误:AttributeError: 'str' object has no attribute 'endsWith' - Razzle
2个回答

5

检查字符串而不是列表的 endswithe.split() 会给出一个列表。迭代这个列表并检查每个项目与列表中的每个项目一起是否以 endswith 结尾。

suffix_list = []

for e in file:
    for element in e.split():
        if element.endswith("a"):
            suffix_list.append(element)

print(len(suffix_list))

此外,还有一种使用列表推导式的版本:
suffix_list = [] 
for e in file:
    suffix_list.extend([element for element in e.split() if element.endswith('a')])

假设你需要一个扁平的列表而不是列表嵌套。

1
或者...嵌套的列表推导式:suffix_list = [el for e in file for el in e.split() if el.endswith('a')]... - Jon Clements

0
for e in file:
    elements=e.split()
    result=[ele for ele in elements if ele.endswith("a")]
    suffix_list.append(result)

1
我很确定 OP 希望输出一个平面列表,因为他们想要通过使用 len 来获取匹配单词的总数。所以,你可以使用 .extend 而不是使用 .append - PM 2Ring

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接