把元组变成成对的字符串

2024-06-22 10:42:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下元组

[   ('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)]

我要创建的是创建一个如下所示的字符串:

^{pr2}$

如何在Python中方便地实现这一点?在


Tags: 字符串元组pr2neutrophilsmonocytesmacrophagesnkcellsstromalcells
3条回答
>>> l = [   ('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)]


>>> ['%s(%.2f)' % (f, d) for f,d in l]
['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)']

>>> ', '.join(['%s(%.2f)' % (f, d) for f,d in l])
'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)'
', '.join('%s(%.02f)' % (x, y) for x, y in tuplelist)

我不觉得有什么困难:

tuples = [   ('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)]
print ', '. join('%s(%.02f)' % (name, value) for name, value in tuples)

相关问题 更多 >