Python 在多个列表中打印完整项目
我试图打印两个列表,但它只打印列表中每个项目的第一个字母Python 在多个列表中打印完整项目,python,string,python-2.7,list,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
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
如何完整打印字符串?从
格式中删除*
将适用于您:
>>> 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
解释:*我的列表
解压列表。由于字符串也是字符的列表
,'-{0}。格式(*x)
将变成:'-{0}。格式(['h','e','l','l','o'])
。因此,它只是在['h','e','l','l','o']
的第0个索引处插入字符串,即h
备选方案
>>> 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'
要生成完整的输出,上述操作将同时针对lst1
和lst2
执行,并与'\n.连接(…)
为什么要使用.format(*x)
?您认为这格式(*x)
有什么作用?请删除x
前面的*
。星星把绳子解压成一个字符列表。也许吧?您预期的结果是什么?@njzk2抱歉,由于某种原因,将解包元组的过程弄混了。谢谢