Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

Python 自定义列表输出

Python 自定义列表输出,python,python-3.x,Python,Python 3.x,我有以下清单: sampleList=['a','b','c','d'] 我需要按如下方式显示列表元素: a, b, c and d 我试图将“,”与每个列表元素连接起来。然而,我没有得到预期的结果 ','.join(sampleList) 每个列表元素在最后一个元素(如a、b、c和d)之前用逗号和关键字“and”隔开。没有内置的方法来实现这一点。你必须自己动手 ', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1]) 输出:

我有以下清单:

sampleList=['a','b','c','d']
我需要按如下方式显示列表元素:

a, b, c and d
我试图将“,”与每个列表元素连接起来。然而,我没有得到预期的结果

','.join(sampleList)

每个列表元素在最后一个元素(如a、b、c和d)之前用逗号和关键字“and”隔开。

没有内置的方法来实现这一点。你必须自己动手

', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1])
输出:

>>> sampleList = ['a', 'b', 'c', 'd']
>>> ', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1])
'a, b, c and d'
>>>
使用str.join尝试此代码,使用[::-1]和str.replace反转。这有点像黑客攻击:

>>> sampleList=['a','b','c','d']
>>> s = ', '.join(sampleList)
>>> s[::-1].replace(' ,', ' dna ', 1)[::-1]
'a, b, c and d'
>>> 

为此,您可以对n-1个元素执行相同的操作,并通过“and”连接最后一个元素:

L=['a','b','c','d']
l=L[:-1] #get all except the last element
st=l.join(',')
sf= st+' and '+L[-1]
#sf=a,b,c and d