我用Python 2.7.9成对打印出单词及其含义。我将单词存储在列表中,将含义存储在另一个列表中。 假设我已定义:
word=['a','the','go','python']
meaning=['meaning1','meaning2','veryveryveryveryveryverylongmeaning3','meaning4']
我希望输出如下:
a meaning1
the meaning2
go veryveryveryveryvery
verylongmeaning3
python meaning4
问题是std lib中的textwrap模块只打破了长期的含义'单词到嵌套列表而不在单词列表中相应添加新行。在包装了'意义'中包含了多少行后,我也不知道。还有其他编码技巧吗?
答案 0 :(得分:2)
那是textwrap.wrap()
的作用;它返回一个行列表,最后没有换行符。你可以随心所欲地做任何事情。
顺便说一句,您应该使用dict
表示单词和含义,或OrderedDict
如果您想保留订单。
import textwrap
from collections import OrderedDict
words = ['a', 'the', 'go', 'python']
meanings = ['meaning1', 'meaning2', 'meaning3',
'Python is a programming language that lets you work more quickly '
'and integrate your systems more effectively. You can learn to '
'use Python and see almost immediate gains in productivity and '
'lower maintenance costs.']
wrapped_meanings = ['\n'.join(textwrap.wrap(meaning)) for meaning in meanings]
dictionary = OrderedDict(zip(words, wrapped_meanings))
for word, meaning in dictionary.items():
print word
print meaning
print
输出:
a
meaning1
the
meaning2
go
meaning3
python
Python is a programming language that lets you work more quickly and
integrate your systems more effectively. You can learn to use Python
and see almost immediate gains in productivity and lower maintenance
costs.
答案 1 :(得分:1)
使用enumerate
浏览列表,format
格式化字符串输出,join
以合并含义。
word=['a','the','go','python']
meaning= [['meaning1'], ['meaning2'], ['veryveryve', 'ryveryvery', 'veryveryve', 'ryveryvery', 'veryveryve', 'ryveryvery', 'veryverylo', 'ngmeaning3'], ['meaning4']]
for i, value in enumerate(word):
print "{}\t{}".format(value, "\n\t".join(meaning[i]))
a meaning1
the meaning2
go veryveryve
ryveryvery
veryveryve
ryveryvery
veryveryve
ryveryvery
veryverylo
ngmeaning3
python meaning4
答案 2 :(得分:0)
你将无法连接list和str
print str(word[i])+'\t'+str(meaning[i])