python - 有没有更好的方法来完成这个 python 练习? (初学者)

标签 python python-3.x

我刚刚开始学习 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/

相关文章:

python - 更改时区后在 Python 中获取系统日期/时间

python - 使用 python 为 Google Play Developer API 使用 oauth2 授权服务帐户

python-3.x - 比较 Pandas 中的 ID 日期组合

python - 将 JSON 日期字符串规范化为 UTC python

python-3.x - 如何正确地将依赖项注入(inject) Flask?

Python 属性错误 : 'module' object has no attribute 'DIST_L2'

python - 确定文本文件中句子、单词和字母的数量

python - 使用python将文件夹中的所有pdf转换为文本文件并将它们存储在不同的文件夹中

python-3.x - KivyMD 中 MDDropdownMenu 的定位错误

python-3.x - 异常 : Layout must be a dash component or a function that returns a dash component