我有一个列表,它是我代码的输出,我想在这个列表中进行更多的操作。我已经编写了代码,将输入列表中的范围转换为具有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"
谢谢。在
因此
newlist
是元组列表的列表,而期望的输出也是元组列表的列表。但是,pList
的表达式生成元组列表。看起来你只需要再加上一个列表理解就可以了。在这样可以解决您的问题:
生成的输出为:
^{pr2}$提示
使用导入pprint;pprint.pprint用于打印复杂的数据结构
会印得像
这是一个简单的拆包变化。将
for i in newlist
替换为for s, i in newlist[e]
:另外,如果使用named tuples,这种数学分析的可读性会大大提高。在
相关问题 更多 >
编程相关推荐