lis内容的数学运算

2024-04-27 02:31:56 发布

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

我有一个列表,它是我代码的输出,我想在这个列表中进行更多的操作。我已经编写了代码,将输入列表中的范围转换为具有3个选项的单个值。在

newlist = [[('s', [(0.0, 0.3), (0.1, 0.8), (0.0, 1.0), (0.0, 0.0), (0.0, 0.5)]), 
            ('aa', [(0.0, 0.3), [0.1, 0.8], (0.0, 1.0), [0.0, 1.0], (0.0, 0.5)])], 
          [('m', [(0.0, 0.0), (0.0, 0.0), (0.1, 0.5), (0.0, 0.8), (0.0, 0.0)]), 
           ('ih', [(0.0, 0.0), (0.1, 0.8), (0.1, 0.5), (0.0, 0.4), (0.0, 0.0)])]] 

e = int(raw_input("\n Choose the energy level of the speaker: \n '1' for low \n '2' for normal \n '3' for high \n"))

if e == 1 :
    pList = [(i[0], [j[0] for j in i[1]]) for i in newlist]

elif e == 2:
    pList = [(i[0], [(float(j[0]) + float(j[1])) / 2.0 for j in i[1]]) for i in newlist]

elif e == 3:
    pList = [(i[0], [j[1] for j in i[1]]) for i in newlist]    

print pList

选择1时,输出应为

^{pr2}$

选择2的输出应该是

pList = [[('s', [(0.15, 0.45, 0.5, 0.0, 0.25)]), 
          ('aa', [(0.15, 0.45, 0.5, 0.5, 0.25)])], 
        [('m', [0.0, 0.0, 0.3, 0.4, 0.0)]), 
         ('ih', [(0.0, 0.45, 0.3, 0.2, 0.0)])]] 

选择3的输出应该是

pList = [[('s', [(0.3, 0.8, 1.0, 0.0, 0.5)]), 
          ('aa', [(0.3, 0.8, 1.0, 1.0, 0.5)])], 
        [('m', [(0.0, 0.0, 0.5, 0.8, 0.0)]), 
         ('ih', [(0.0, 0.8, 0.5, 0.4, 0.0)])]] 

所有的选择都不起作用。我想我在指数上犯了错误。选项2给出的错误是

"ValueError: invalid literal for float(): a"

谢谢。在


Tags: the代码in列表forraw选项错误
3条回答

因此newlist是元组列表的列表,而期望的输出也是元组列表的列表。但是,pList的表达式生成元组列表。看起来你只需要再加上一个列表理解就可以了。在

这样可以解决您的问题:

print [[(j, [(float(x[0]) + float(x[1])) / 2.0 for x in e]) for j,e in i] for i in newlist]

生成的输出为:

^{pr2}$

提示

使用导入pprint;pprint.pprint用于打印复杂的数据结构

import pprint; pprint.pprint([[(j, [(float(x[0]) + float(x[1])) / 2.0 for x in e]) for j,e in i] for i in newlist])

会印得像

~$ python ~/test.py 
[[('s', [0.15, 0.45, 0.5, 0.0, 0.25]), ('aa', [0.15, 0.45, 0.5, 0.5, 0.25])],
 [('m', [0.0, 0.0, 0.3, 0.4, 0.0]), ('ih', [0.0, 0.45, 0.3, 0.2, 0.0])]]

这是一个简单的拆包变化。将for i in newlist替换为for s, i in newlist[e]

>>> newlist = [[('s', [(0.0, 0.3), (0.1, 0.8), (0.0, 1.0), (0.0, 0.0), (0.0, 0.5)]),
            ('aa', [(0.0, 0.3), [0.1, 0.8], (0.0, 1.0), [0.0, 1.0], (0.0, 0.5)])],
          [('m', [(0.0, 0.0), (0.0, 0.0), (0.1, 0.5), (0.0, 0.8), (0.0, 0.0)]),
           ('ih', [(0.0, 0.0), (0.1, 0.8), (0.1, 0.5), (0.0, 0.4), (0.0, 0.0)])]]
>>> e = 1
>>> [(s, [t[0] for t in lot]) for s, lot in newlist[e]]
[('m', [0.0, 0.0, 0.1, 0.0, 0.0]), ('ih', [0.0, 0.1, 0.1, 0.0, 0.0])]

另外,如果使用named tuples,这种数学分析的可读性会大大提高。在

相关问题 更多 >