V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
leegradyllljjjj
V2EX  ›  Python

Python 求问怎么改嵌套 list 或者 tuple 里的某个层的某个值,套娃是大坑啊

  •  
  •   leegradyllljjjj · Dec 1, 2020 · 2497 views
    This topic created in 1979 days ago, the information mentioned may be changed or developed.

    事情是这样的,有一个嵌套列表,列表里嵌套的东西类型不确定。比如: [1,2,3,4,[9,5,6,7]] 以及 [Float(2.423),2,4,2,[],[Float(2.312)]] 还有 (Flaot(2.453),(2.231,9,8,7),1.2234,2.333) 甚至还有(Float(1.222),5.225,"this is string")

    现在的问题是 Float()这种 sympy 里的类型直接序列化报错,所以只有找到这些类型的数据然后处理, 请问有没有简易的办法呢?

    1.找到 Float 类型数据并使用 float()替换 2. 保持原来的结构 3. 处理过后是 list 嵌套或者 tuple 嵌套都无所谓

    4 replies    2020-12-01 22:53:52 +08:00
    XiaoxiaoPu
        1
    XiaoxiaoPu  
       Dec 1, 2020
    用的什么序列化方式? json 是支持对象特殊处理的,你是用的序列化方式可能也有响应的支持
    leegradyllljjjj
        2
    leegradyllljjjj  
    OP
       Dec 1, 2020
    simplejson.dumps(data),里面的 Float 特殊类型就报错,只好转换成 python 基本类型
    SaltCat
        3
    SaltCat  
       Dec 1, 2020
    使用 json.dumps 的 default 参数:

    ```
    json.dumps(sth, default=lambda x: x.toNative() if isinstance(x, MyCustomFloat) else None)
    ```
    SaltCat
        4
    SaltCat  
       Dec 1, 2020
    我好久都不用直接 json 序列化了, 上次用是 custom FastAPI 的 Response, 自己造了个 OrjsonResponse(后面官方提供了), 就用了 singledispacherxxxxx 和这个特性.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   979 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 23:41 · PVG 07:41 · LAX 16:41 · JFK 19:41
    ♥ Do have faith in what you're doing.