【问题标题】:Trying to generate a list using python script [duplicate]尝试使用python脚本生成列表[重复]
【发布时间】:2015-10-19 14:35:29
【问题描述】:

我正在尝试生成一个列表 python。在这个程序中,我正在尝试编写一个函数,该函数从键盘获取列表值并返回一个字符串,其中所有项目由逗号和空格分隔,并在最后一项之前插入 "and"。 例如,将前一个垃圾邮件列表传递给函数将返回 '苹果、香蕉、豆腐和猫'。她是我的密码

spam=[]

def rock(val):
    while True:
        print("Enter the text: ")
        val=input()
        spam.append(val)
        return spam


print("Enter the number: ")
n=int(input())
for i in range(0,n):
    s=', '.join(rock(''))
    print(s)

Output:
Enter the number: 
3
Enter the text: 
rock
rock
Enter the text: 
dog
rock, dog
Enter the text: 
cad
rock, dog, cad

现在,在上面提到的程序中,我已经成功生成了一个用逗号分隔的列表。但我不知道如何将 "and" 放在最后一个值之前。像这样,'苹果、香蕉、豆腐和猫'

【问题讨论】:

    标签: python python-2.7 python-3.x


    【解决方案1】:

    只需使用“,”连接列表的头部,然后使用“, and”连接,例如:

    words = ["apples", "bananas", "tofu", "cats"]
    
    head = ", ".join(words[:-1])
    result = ", and ".join( [head, words[-1]] )
    
    print(result)
    

    (最后一个可以直接连接:`result = head + ", and " + words[-1])

    【讨论】:

    • 语法错误。
    • @Jordan 你从哪里得到语法错误?我已经使用pythonpython3 进行了验证。我已经用示例输入数据和结果的打印输出更新了答案。
    • 非常感谢代码运行良好。
    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 2018-08-06
    • 2021-08-31
    • 2020-10-03
    • 1970-01-01
    • 2021-02-12
    • 2016-11-29
    • 1970-01-01
    相关资源
    最近更新 更多