我刚刚开始学习 Python,我将在本章末尾进行练习。到目前为止,我在书中学到的只是非常基础的知识、流控制、函数和列表。
练习是:
逗号代码
假设您有一个这样的列表值:
垃圾邮件 = ['苹果', '香蕉', ' bean 腐', '猫']
编写一个将列表值作为参数并返回的函数
一个由逗号和空格分隔的所有项目的字符串,带有“和”
插入到最后一项之前。例如,将之前的垃圾邮件列表传递给
该函数将返回“苹果、香蕉、 bean 腐和猫”。但是你的功能
应该能够处理传递给它的任何列表值。
为了解决这个问题,我使用了以下代码 (python 3.x.x)。我想知道是否有更好的方法来做到这一点。它经过了一些反复试验,但我摸索着直到得到这个:
myList = ['apples', 'bananas', 'tofu', 'cats']
myList2 = ['apples', 'bananas', 'tofu', 'cats', 'added1', 'added2']
def listFunc(List):
x = 0
for i in List:
x += 1
if x < len(List):
print(i, end=' ')
elif x == len(List):
print('and ' + i)
listFunc(myList2)
最佳答案
实现此目的的另一种方法是使用切片和连接:
def listFunc(lst):
if len(lst) == 0: return ''
if len(lst) == 1: return lst[0]
return ", and ".join([", ".join(lst[:-1]), lst[-1]])
下面是使用相同核心概念的上述函数的更具可读性的版本。
def listFunc(lst):
if len(lst) == 0: return '' #no elements? empty string
if len(lst) == 1: return lst[0] #one element? no joining/separating to do, just give it back
firstPart = lst[:-1] #firstPart is now everything except the last element
retFirst = ", ".join(firstPart) #retFirst is now the first elements joined by a comma and a space.
retSecond = ", and " + lst[-1] #retSecond is now ", and [last element]"
return retFirst + retSecond;
我认为这里唯一可能令人困惑的位是切片语法、负索引和 string.join
lst[:-1]
的意思是获取 lst 中除最后一个元素之外的所有内容
这是一个列表切片
代码lst[-1]
的意思是获取lst中的最后一个元素
这是负索引
最后,代码 ", ".join(firstPart)
表示获取一个字符串,其中包含 firstPart 中的每个元素,以逗号和空格分隔
关于python - 有没有更好的方法来完成这个 python 练习? (初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782030/