在多个列表中打印完整项目

时间:2016-08-22 20:30:57

标签: python string python-2.7 list

我正在尝试打印两个列表,但它只打印列表中每个项目的第一个字母;

lst1 = ['hello', 'hi', 'sup']
lst2 = ['bye', 'cya', 'goodbye']

for item in [lst1, lst2]:
    print 'Your options are: ' + ' '.join(['-{0}'.format(*x) for x in item])

结果;

You can choose: -h -h -s
You can choose: -b -c -g

如何完整打印字符串?

2 个答案:

答案 0 :(得分:4)

*删除format对您有用:

>>> for item in [lst1, lst2]:
...     print 'Your options are: ' + ' '.join(['-{0}'.format(x) for x in item])
... 
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye

解释*my_list解压缩列表。由于,字符串也是list的{​​{1}},chars将变为:'-{0}'.format(*x)。因此,它只是将字符串插入'-{0}'.format(['h', 'e', 'l', 'l', 'o'])的第0个索引,即['h', 'e', 'l', 'l', 'o']

答案 1 :(得分:0)

替代;

>>> print '\n'.join('Your options are: -%s' % ' -'.join(x) for x in (lst1, lst2))
Your options are: -hello -hi -sup
Your options are: -bye -cya -goodbye

如何运作

生成一行输出:

>>> 'Your options are: -%s' % ' -'.join(lst1)
'Your options are: -hello -hi -sup'

要生成完整的输出,上述内容适用于lst1lst2,并与'\n'.join(...)结合使用。