Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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,我正在尝试解决逗号代码项目,以使无聊的事情自动化。我在第一个if语句中遇到了问题。我试图输出字符串:“苹果、香蕉、豆腐和猫”。出于某种原因,它跳过了列表中的第一项 编辑:本教程没有教授连接方法,因此我现在不使用它。此外,我的程序需要处理所有大小的列表 我想我应该做以下事情,但我一直得到UnboundLocalError:在赋值之前引用局部变量'first' if i < len(list[0:-2]): first += list[i] + ',' 如果i

我正在尝试解决逗号代码项目,以使无聊的事情自动化。我在第一个if语句中遇到了问题。我试图输出字符串:“苹果、香蕉、豆腐和猫”。出于某种原因,它跳过了列表中的第一项

编辑:本教程没有教授连接方法,因此我现在不使用它。此外,我的程序需要处理所有大小的列表

我想我应该做以下事情,但我一直得到UnboundLocalError:在赋值之前引用局部变量'first'

if i < len(list[0:-2]):
    first += list[i] + ',' 
如果i
我的代码:

def myList(list):

    for i in range(len(list)+1):

        if i < len(list[0:-2]):    
            first = list[i] + ',' 
        elif i == len(list[0:-1]):
            second = list[-2]+ ' and '
        elif i == len(list[0:]):
            last = list[-1]

    print(first +second +last)            




spam = ['apples', 'bananas', 'tofu', 'cats']
#list index 0 1 2 3

myList(spam)
def myList(列表):
对于范围内的i(长度(列表)+1):
如果i
我的产品是香蕉、豆腐和猫

编辑:我用谷歌搜索的解决方案是for循环中的全局变量

def myList(list):

    for i in range(len(list)):

        if i < len(list[0:-2]):
            global first
            first += list[i] + ',' 
        elif i == len(list[0:-1]):
            global second
            second = list[-2]+ ' and '
        elif i == len(list[0:]):
            global last
            last = list[-1]

    print(first +second +last)            




spam = ['apples', 'bananas', 'tofu', 'cats']
#list index 0 1 2 3

myList(spam)
def myList(列表):
对于范围内的i(len(列表)):
如果i
我的输出现在是
香蕉、苹果、香蕉、苹果、香蕉、苹果、香蕉、苹果、香蕉、苹果、香蕉、苹果、香蕉、豆腐和猫

只需在函数开始时首先声明即可

def myList(list):
         first=""
         for i  in range(len(list)+1):

             if i < len(list[0:-2]):    
                 first =first+ list[i] + ','
             elif i == len(list[0:-1]):
                 second = list[-2]+ ' and '
             elif i == len(list[0:]):
                 last = list[-1]

         print(first +second +last) 
def myList(列表):
first=“”
对于范围内的i(长度(列表)+1):
如果i
下次尝试将print语句放在所有地方,并自行调试代码

尝试以下操作-

def myList(spam):
    s = ''
    for i in range(len(spam)):
        if i == len(spam) - 1:
            s+= "and "+spam[i]
        else:
            s+= spam[i]+", "
    print(s)

myList(spam)
或者使用
join
-

print(', '.join(spam[:-1]) + ', and ' + spam[-1])

读取切片列表的长度很复杂。试试这个,不要硬编码:

def myList(list):
    if len(list) <= 2:
        print(' and '.join(list))
    else:
        print(', '.join(list[:-1]) + ', and ' + list[-1])
def myList(列表):
如果len(list)
***请尝试将以下代码作为单独的功能:***
def myList(列表):
returnString=''
如果len(列表)>0且len(列表)>2:
列表\计数=len(列表)-1
对于idx,枚举(列表)中的元素:
++idx
如果idx==列表计数:
returnString+=“和%s”%元素
其他:
returnString+=%s,“%s”元素

elif len(列表)以下是我如何解决这个问题的:

def listToString (list):
    output = ''
    for items in list[:-1]: # Grabs all items from the list except the final one
        output+= items + ', ' 
    output+= 'and ' + list[-1] + '.' # Adds the final value of the list.
    print(output)

testList = ['Apples','Oranges', 'Pears', 'Bananas']
listToString(testList)

我也在用这本书学习python,我发现这个解决方案只使用了直到这个问题之前所教的函数

spam = [ 'apples', 'bananas', 'tofu', 'cats']

def Commacode(n):
    a = ''
    if len(n) == 1:
        print(n[0])
    else:
        for i in range(len(n) - 2):
            a = a + n[i] + ', '
        print(a + n[-2] + ' and ' + n[-1])

Commacode(spam)
输出:

apples, bananas, tofu and cats

我现在正在写这本书(第二版),所以我是一个完全的初学者。我对这项工作的答复是:

spam = ['apples', 'bananas', 'tofu', 'cats']
            
def comma_code(source):
    source_string = ''
    try:
        if len(source) == 1:
            print(str(source[0]) + '.')
        else:    
            for item in source[:-2]:
                source_string = source_string + str(item) + ', '
            print(source_string + str(source[-2]) + ' and ' + str(source[-1]) + '.')
        
    except IndexError:
        return

comma_code(spam)
结果是:

苹果、香蕉、豆腐和猫

如果列表为空:“[]”

如果列表仅包含1项:“[苹果]”

苹果

如果列表是数字:“[1,2,3,4,5]”

1、2、3、4和5

我可以在“除索引器”中“打印”一条消息,以创建一个空列表,而不是只捕获错误。我不使用“加入”,因为这本书还没有涉及到这一点(所以我现在不知道该怎么做)。此函数只打印结果,因此我制作了另一个版本,将返回值存储在变量中,供其他函数使用:

spam = ['apples', 'bananas', 'tofu', 'cats']
            
def comma_code(source):
    source_string = ''
    try:
        if len(source) == 1:
            source_string = str(source[0]) + '.'
            return source_string
        else:    
            for item in source[:-2]:
                source_string = source_string + str(item) + ', '
            source_string = source_string + str(source[-2]) + ' and ' + str(source[-1]) + '.'
            return source_string
    
    except IndexError:
        return


print(comma_code(spam))
我将尝试回答原始消息:

你需要使用一个调试工具,你会发现为什么你的第一个单词会丢失。 我看到的问题在于:

if i < len(list[0:-2]): 
如果i

不是全局变量问题(程序中的所有变量都是局部变量)。“i”获取值“0”,并将“list[0]”添加到变量“first”中,然后第二次运行“i”获取值1,其值仍然小于2,因此它将使用值“list[1]”覆盖“first”变量.

什么是完整的错误回溯?您是否也可以发布预期的输出?请参阅我所做的编辑。您希望将它们存储在不同变量中的原因是什么?第一个变量有问题。我越来越长了outputs@LoveisHell现在就试试谢谢你的意见!我真的这么做了,但我似乎做不好。我无法使它与您的代码一起工作。我想使用全局变量作为答案。我执行了代码,得到了您描述的输出。您再次检查,使用全局变量是不好的,缩进错误现在就尝试一下。它在print语句之后删除了一个额外的空间。Work comp,cannot access非常感谢。最后我忘了插入垃圾邮件列表和调用函数。你能给我解释一下第一个“”的作用吗?为什么第一个变量是空的很重要?在我目前的阶段对我来说太复杂了。还是谢谢你!“有什么想法吗?什么都行。谢谢。”这是一个问题还是一个答案?如果是后者,请删除此行并在需要时打开一个新问题。
if i < len(list[0:-2]):