如何以自定义方式输出数据?

时间:2016-04-12 09:38:23

标签: python loops

我正在尝试输出书籍的名称及其概率。这是当前输出的样子:

Happy Journey, What a Good Life!, Far Far Away, Slow and Steady, The Meeting
(0.94, 0.56, 0.43, 0.24, 0.10)

我想要实现的是将概率与名称配对:

Happy Journey(0.94), What a Good Life!(0.56), Far Far Away(0.43), Slow and Steady(0.24), The Meeting(0.10)

这是我到目前为止所做的事情:

f.write("Top 5 Probable Books:")     

for item in w:
    f.write(d.get(int(item))) #gets the names of the book from a dictionary
    f.write(", ")             # w is a label in the dictionary 
f.write("\n")

这就是我的prob5的样子:[[0.940021 0.561000 0.430012 0.241982 0.100134]]这就是为什么我将它四舍五入到4位小数并且我需要从这个numpy数组中提取概率。

for pk in prob5:
    jk=', '.join("%.4f" %b for b in pk) #picking out probabilities from a numpy array
    jk="("+jk+ ")" + "\t"
    f.write(jk)

我对如何同时运行两个循环以获得所需的输出格式感到有些困惑。

3 个答案:

答案 0 :(得分:2)

我不知道在操作numpy数组时遇到了什么样的问题,但是如果你所描述的prob5可以直接访问它的第0个元素prob5[0]。至于打印4位小数,请查看.format()的语法。

假设您使用的是Python 3:

>>> f.write(', '.join('{}({:.4f})'.format(string, number) for string, number in zip(w, prob5[0])))
Happy Journey(0.9400), What a Good Life!(0.5610), Far Far Away(0.4300), Slow and Steady(0.2420), The Meeting(0.1001)

如果您使用Python 2.x,请使用itertools模块及其izip函数,该函数的性能优于本机zip。如果对象具有不同数量的元素,请改用izip_longest

# example
import itertools
...
f.write(', '.join('{}({})'.format(string, number) for string, number in itertools.izip(w, prob5)))
#f.write(', '.join('{}({})'.format(string, number) for string, number in itertools.izip_longest(w, prob5))) # if w and prob5 have a different number of elements

答案 1 :(得分:1)

您可以使用zip合并两个列表,然后使用itertools grouper分成两组。

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

for group in grouper(zip(w, prob5), 2):
    print(group)

答案 2 :(得分:1)

你的意思是这样吗?

names = ['Happy Journey', 'What a Good Life!', 'Far Far Away', 'Slow and Steady', 'The Meeting']
probabilities = (0.94, 0.56, 0.43, 0.24, 0.10)
myDesiredOutput = ['{}({})'.format(names[n],probabilities[n]) for n,v in enumerate(names)]

>>>myDesiredOutput
['Happy Journey(0.94)',
 'What a Good Life!(0.56)',
 'Far Far Away(0.43)',
 'Slow and Steady(0.24)',
 'The Meeting(0.1)']

并将输出直接写入文件:

with open('out.txt', 'w') as f:
    for item in ['{}({})\n'.format(names[n],probabilities[n]) for n,v in enumerate(names)]:
        f.write(item)

如果您想将输出写入一行,则可以使用'\n'更改','