指定列表中的字符串脚本任何名单。

问题描述 投票:1回答:12

我工作的一个项目,从自动化的第4章的无聊的东西与Python。下面是该项目的提示:

“对于实践,编写程序来执行以下任务逗号码假设你有一个列表值是这样的:垃圾= [”苹果,‘香蕉’,‘豆腐’,‘猫’]编写一个函数,接受一个列表值作为参数,并返回所有的最后一个项目之前,用逗号和空格,以分离和插入的项目的字符串。例如,通过前面的垃圾邮件列表,该函数将返回“苹果,香蕉,豆腐,和猫”但你的函数应该能够传递给它的任何列表值继续工作。”

我写了一个创建带有逗号和列表的脚本“和”最后一个项目之前:但我无法弄清楚如何使脚本工作,传递给它的任何列表值。我已经使用输入函数来调用列表尝试过,但不工作(或我不能去上班),由于输入函数只接收字符串,而不是列出的名字呢?

下面是我得到的最远:

def listToString(list):
    if list[-1]:
        list.append('and '+str(list[-1]))
        list.remove(list[-2])
    for i in range(len(list)):
        print(''+list[i]+', ')

spam = ['apples', 'bananas', 'tofu', 'cats']
listToString(spam)

至于使用输入()函数,这是我一直在努力,都无济于事的代码。我进入外壳编辑器中的垃圾邮件列表,运行以下命令:

def listToString(list):
    if list[-1]:
        list.append('and '+str(list[-1]))
        list.remove(list[-2])
    for i in range(len(list)):
        print(''+list[i]+', ')

list = input("What list do you want to use?")
listToString(list)
python list python-3.x
12个回答
4
投票

这里是只使用已经Chapter 4涵盖语法简单的解决方案:

def toString(arr):
    s = ''
    for i in range(len(arr)):
        if i > 0:
            if i == len(arr) - 1:
                # last one
                s = s + ' and '
            else:
                # second, third, ...
                s = s + ', '
        s = s + arr[i];
    return s

它的工作原理与任何元素数量的数组。


0
投票

我在逗号码的版本:

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

def comma(aList):
    for i in range(len(aList) - 1):
        newList.append(aList[i])
    newList.append('and ')
    myString = ', '.join(newList)
    print(myString + aList[-1])

comma(spam)

0
投票

按照分配,你必须确保“的功能应该能够传递给它的任何列表值继续工作。”这意味着它必须用0,1,1 +列表值工作。

spam = ['green','eggs','ham']

def merge(list):
    if len(list) == 0:
        return None
    elif len(list) == 1:
        return list[0]
    else:
        return ', '.join(list[:-1] + ['and '+list[-1]])

print(merge(spam))

0
投票

这里是非常简单的解决问题的办法:

def lst2str(spam):
    str = ''
    for word in spam:
        if word != spam[-1]:
            spacing = word + ", "
            str += spacing
        else:
            spacing = "and " + word
            str += spacing
    return str

3
投票

我认为,最简单的方法是用替代的最后一个元素“和......”,然后加入与一切“”

def merge(list):
  return ', '.join(list[:-1] + ['and '+list[-1]])

1
投票

我相信,“但是,你的功能应该能够传递给它的任何列表值继续工作。”意味着你应该在功能没有硬编码的例子表([“苹果”,“香蕉”,“豆腐”,“猫”])。

因此,该功能的最简单的形式是:

def listToString(list):
    return "{} and {}".format(", ".join(list[:-1]]), list[-1])

但是,当你要处理其它类型不是字符串和少于2个元素,函数变为:

def listToString(list):
    length = len(list)
    if length == 0 :
        return ""
    elif length == 1 :
        return "{}".format(list[0])
    else:
        strings = ["{}".format(x) for x in list[:-1]]
        return "{} and {}".format(", ".join(strings), list[-1])

1
投票

该解决方案完全基于掩盖了第4章。它使大量使用在第3章提出的“结束”参数的基本原则。

spam = ['apples', 'bananas', 'tofu', 'cats']
print("'", end='')
for i in range(len(spam)-1):
    print(spam[i], end=', ')
print('and '+str(spam[-1]), end='')
print("'")

1
投票

这里是我的解决方案:

spam = ['zero', 'one', 'two', 'three', 'second to last', 'last']

def func(listValue):
    print('\'', end='')    # Openning single quote.
    for i in range(len(listValue[:-2])):    # Iterate through all values in the list up to second to last.
        print(str(listValue[i]), end=', ')
        continue
    print(str(listValue[-2]) + ' and ' + str(listValue[-1]) + '\'')    # Add second to last and last to string separated by 'and'. End with a single quote.

listValue = spam
func(listValue)

    # Will do for any list.

输出是:

“零,一,二,三,倒数第二个和最后一个”


0
投票

下面是我对这个问题的解决方案。随着我的每一行代码的注释。希望这可以帮助。

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

# function should return 'apples, bananas, tofu, and cats' 

def listToString(list):

    newString = '' # create an empty string variable 

    # for loop that iterates through length of list 
    for index in range(len(list)):
        # put a comma and space after each word except the last one 
        if index in range(len(list)-1): 
            newString += list[index] + ',' + ' '
        else:
            newString += 'and' + ' ' #put the word and + a space
            #finally put the last word from the list 
            #spam in the string newString
            newString += list[index] 

       #return newString value
       return '{}'.format(newString) 

listToString(spam)

输出:

'apples, bananas, tofu, and cats'

0
投票

这是我想出了学习蟒蛇一周后的解决方案:

spam = ['apples', 'bananas', 'tofu', 'cats', 'rats', 'turkeys']
group = []
for i in range(len(spam)-1):
    group.append(spam[i])
print (', '.join(group),'& ' +spam[-1])

我只是在这个问题上的工作今天我的新的Python的爱好中。

我知道我的解决方案是不是很紧凑,优雅的顶级之一。我基本上只是使用的语句来创建第二个列表W / O中的最后一项,然后用于打印加入该组中添加了“&”符号,最后的最后一个项目。


0
投票

这是我想出了。

spam = ['apples', 'bananas', 'tofu', 'cats']
spam.insert(-1, ' and')
print(spam[0] + ', ' + spam[1] + ', ' + spam[2] + ',' + spam[3] + ' ' + spam[4])

0
投票

这是我的解决办法

def converter(mylist):
    mystr=''
    if len(mylist)>1:
        for i in range(len(mylist)-1):
            mystr=mystr+str(mylist[i])+', '
        mystr=mystr+'and '+str(mylist[-1])
        print(mystr)
    elif len(mylist)==1:    
        mystr=mystr+str(mylist[0])
        print(mystr)
    else:
        print('Your list is empty')
spam = []
t='1'
while t != '':
    print('Input new value in list (Or enter nothing to stop)')
    t=str(input())
    if t != '':
        spam.append(t)
converter(spam)
© www.soinside.com 2019 - 2024. All rights reserved.