python - 将成对字符串转换为元组

标签 python

我有以下字符串:

my_str = "StemCells(16.53),Bcells(13.59),Monocytes(11.58),abTcells(10.05),Macrophages(9.69),  gdTCells(9.49),StromalCells(9.36),DendriticCells(9.20),NKCells(7.81),Neutrophils(2.71)"

我想做的是将它们转换成这个元组

[   ('StemCells', 16.530000000000001),
    ('Bcells', 13.59),
    ('Monocytes', 11.58),
    ('abTcells', 10.050000000000001),
    ('Macrophages', 9.6899999999999995),
    ('gdTCells', 9.4900000000000002),
    ('StromalCells', 9.3599999999999994),
    ('DendriticCells', 9.1999999999999993),
    ('NKCells', 7.8099999999999996),
    ('Neutrophils', 2.71)]

我怎样才能在 Python 中方便地做到这一点

最佳答案

my_str = "StemCells(16.53),Bcells(13.59),Monocytes(11.58),abTcells(10.05),Macrophages(9.69),  gdTCells(9.49),StromalCells(9.36),DendriticCells(9.20),NKCells(7.81),Neutrophils(2.71)"

import re

stuff = re.findall(r'(\w+)\(([0-9.]+)\)',my_str)

stuff
Out[4]: 
[('StemCells', '16.53'),
 ('Bcells', '13.59'),
 ('Monocytes', '11.58'),
 ('abTcells', '10.05'),
 ('Macrophages', '9.69'),
 ('gdTCells', '9.49'),
 ('StromalCells', '9.36'),
 ('DendriticCells', '9.20'),
 ('NKCells', '7.81'),
 ('Neutrophils', '2.71')]

这让你完成了大部分工作,然后就是一些类型转换

[(s,float(f)) for s,f in stuff]
Out[7]: 
[('StemCells', 16.53),
 ('Bcells', 13.59),
 ('Monocytes', 11.58),
 ('abTcells', 10.05),
 ('Macrophages', 9.69),
 ('gdTCells', 9.49),
 ('StromalCells', 9.36),
 ('DendriticCells', 9.2),
 ('NKCells', 7.81),
 ('Neutrophils', 2.71)]

关于python - 将成对字符串转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367605/

相关文章:

python - Netcat 断开连接时自动重新连接

python - 在 Python 中转置 3D 列表

python - 跳过生成器函数中的值

python - 从具有不同键但相同 id 的现有字典创建新的 python 字典

python - 为二进制分类任务嵌入分类数据的正确方法是什么

python - Airflow - GoogleCloudStorageToBigQueryOperator 不呈现模板化的 source_objects

python - 在没有 Redis 的情况下使用 celery 4

python - 'QuerySet' 从 Django 1.4 到 1.7 的变化

python - 在 Django 中同时运行多个网络爬虫

python - Python有同步吗?