[英]mathematical operations on the contents of a list
我有一个列表,该列表是我的代码的输出,并希望在此列表中进行更多操作。 我编写了将输入列表中的范围转换为具有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,输出应为
pList = [[('s', [(0.0, 0.1, 0.0, 0.0, 0.0)]),
('aa', [(0.0, 0.1, 0.0, 0.0, 0.0)])],
[('m', [(0.0, 0.0, 0.1, 0.0, 0.0)]),
('ih', [(0.0, 0.1, 0.1, 0.0, 0.0)])]]
选择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"
谢谢。
这是一个简单的更改。 将for i in newlist
替换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])]
PS如果使用命名元组,这种数学分析将变得更加易读。
这应该可以解决您的问题:
print [[(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])]]
小费
使用import 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])]]
因此, newlist
是元组列表的列表,并且所需的输出是元组列表的列表。 但是您的pList
表达式pList
生成元组列表。 看起来您只需要在其周围包装列表理解即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.