【问题标题】:Pick elements from list and print them in 2-decimal format从列表中选择元素并以 2 位十进制格式打印它们
【发布时间】:2024-01-24 10:19:02
【问题描述】:

我有 2 个列表:一个用于索引(以下vv),另一个用于浮点数(以下aa)。我想用 Python 2.7 做两件事。

(1) 使用vvaa 中挑选元素以创建一个新列表ww

(2) 以 2 位十进制格式打印 ww。 指数的数量不同。我设法用下面的代码做到了这些

# A list of indices
vv = [1, 2, 4]
# A list of floats
aa = [31.123456, 37.354135, 41.987438, 43.458713, 52.687135, 65.321486]

ww = []
for ii in vv:
    ww.append(aa[ii])

print "Indices ", vv, "correspond to [",
for ff in ww:
    print "%.2f," % ff,

print "]"

它的输出是:

    Indices  [1, 2, 4] correspond to [ 37.35, 41.99, 52.69, ]

但我不满足于此。对于 (1),是否有一种更 Pythonish 的方式来做到这一点,对于 (2),输出看起来不像我想要的那样,因为末尾有一个太多的逗号,并且周围有额外的空格括号。它应该看起来像

    Indices  [1, 2, 4] correspond to [37.35, 41.99, 52.69]

当然可以使用任意数量的索引。寻找类似的帖子,他们似乎总是有一个固定的、预先知道的索引数量。我猜list comprehension 会以某种方式解决问题吗? https://*.com/a/16986985/11199684

中提到了这一点

【问题讨论】:

    标签: python python-2.7 list formatting


    【解决方案1】:

    您可以使用join 来做到这一点:

    ww = [round(aa[elem],2) for elem in vv]
    print('Indices ' + ','.join(map(str,vv)) + ' correspond to [' + ', '.join(map(str,ww)) + ']')
    

    结果:

    Indices 1,2,4 correspond to [37.35, 41.99, 52.69]
    

    【讨论】:

    • 谢谢。实际上,在像这样定义 ww 之后,在这个例子中似乎只需 print "Indices ", vv, "correspond to", ww 就足够了,但我很高兴学习 str/join/map 技巧。
    【解决方案2】:

    如果 python 2.7 或更高版本

    print ("Indices ", vv, "correspond to",[round(aa[x], 2) for x in vv])
    

    试试这个

    【讨论】:

    • 这已经很接近了,但还没有:输出是('Indices ', [1, 2, 4], 'correspond to', [37.35, 41.99, 52.69])
    • 为此你只需要格式化你的打印语句。我只是给出了如何列出理解的想法。