ATBS:逗号代码

2024-05-28 11:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解决逗号代码项目来自动化那些无聊的东西。我在处理第一个if语句时遇到了问题。我试图输出字符串:“苹果、香蕉、豆腐和猫”。不知为什么它跳过了列表中的第一项。你知道吗

编辑:教程没有教join方法,所以我现在不使用它。此外,我的程序还需要处理所有大小的列表

我想我应该做以下操作,但是我不断得到UnboundLocalError:赋值前引用的局部变量'first'

if i < len(list[0:-2]):
    first += list[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)

我的产品是香蕉、豆腐和猫

编辑:我在谷歌搜索的解决方案是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)

我的输出现在是 香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,苹果,香蕉,香蕉,豆腐和猫


Tags: 代码苹果forlenifspamgloballist
3条回答

试试这个-

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(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) 

下次试着把print语句放在所有地方,自己调试代码

相关问题 更多 >