Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在多个列表中打印完整项目_Python_String_Python 2.7_List - Fatal编程技术网

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抱歉,由于某种原因,将解包元组的过程弄混了。谢谢