python - findall() 返回一个列表,但它不添加列表中的元素
问题描述
import re
nos="to do with your newfound skills. 338 3803"
for x in nos:
y=re.findall("[0-9]+",nos)
print("total is :",sum(y))
尽管变量 y 返回一个列表,但仍然必须明确提及 y=list() ,它也会给出此错误:
“TypeError:+ 的不支持的操作数类型:'int' 和 'str'”
解决方案
您已经有答案解释了为什么它在评论部分不起作用,但在这种情况下请考虑列表理解,
nos="to do with your newfound skills. 338 3803"
print(sum([int(s) for s in nos.split() if s.isdigit()]))
>>>>4141
甚至更好,正如@EdwardMinnix 所说
print(sum(int(s) for s in nos.split() if s.isdigit()))
推荐阅读
- sql - 将 ActiveRecord 对象转换为数组
- geoserver - 如何从 Openlayer 请求优化 GeoWebcache 的响应速度或性能
- java - EntityManagerFactory 使用 Springboot 和 Elide 为空
- html - 是个
只是一个糟糕的选择 ? - c++ - 赋值后矩阵为零。C++犰狳
- promise - 测试是否调用了带有 Promise 的方法 (Jest)
- c++ - 红黑树空指针 v Nil Leaf
- objective-c - 为什么 Xcode 自动完成总是将我的自定义代码片段置于实际完成之上?
- session - 在 SessionAwareMessageListener 中不起作用 rollback()
- php - 我想[“从表'bid_products'中选择'user_id' where product_id like '$productid' and max_value(bid_amount)]