python - Python 无法正确识别字符串长度?

标签 python list

我有以下Python代码,它应该读取这个列表。如果单词的长度不是 3,则应从列表中删除该单词:

stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]

for word in stuff:
    if len(word) == 3:
        pass
    else:
        stuff.remove(word)

print(stuff)

但是当我打印列表时,我得到以下输出:

['jam', 'bread', 'orange', 'tea']

但它应该看起来像这样:

['jam', 'tea']

非常感谢您的帮助!

最佳答案

在迭代列表时不应从列表中删除元素,因为某些元素可能会被跳过。您可以改用列表理解。

stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]
res = [word for word in stuff if len(word) == 3]
print(res)

关于python - Python 无法正确识别字符串长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70086121/

相关文章:

python - Drupal 或 Wordpress CMS 作为社交网络?

Python pandas 函数根据另一行中的重复值将不同值连接到一列中

python - 使用 re.sub 替换模式

python - Python 3 中 list() 和 [ ] 的区别

java - 根据接口(interface)信息创建列表

python - 传递给有序字典创建的列表理解正在被创建作为引用

r - 如何在列表的元素中存储多个向量?

c# - "Access to the path ' D :\\Windows\\system32\\file is denied"Azure Web App

python - lambda 申请: Referencing other rows and columns

list - 如何在 elm 中按索引获取列表项?