input()函数按字面形式接收条目,而不是生成lis

2024-09-27 23:23:28 发布

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

逗号代码 假设您有这样一个列表值:

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

Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

我最近得到了一个朋友的帮助,帮助我编写了这个代码。你知道吗

list = ['thing1', 'thing2', 'thing3', 'thing4']
def ryansthing(list):
    string = ''
    for i in range(len(list)):
        if not i > len(list) - 2:
            string += list[i] + ', '
        else:
            string += 'and ' + list[i] + '.'
    print(string)

ryansthing(list)

它可以工作(打印出thing1,thing2,thing3和thing4.),但是每当我把代码改成:

list = input() <----- I changed this to input function instead of setting the variable manually.
def ryansthing(list):
    string = ''
    for i in range(len(list)):
        if not i > len(list) - 2:
            string += list[i] + ', '
        else:
            string += 'and ' + list[i] + '.'
    print(string)

ryansthing(list)

它将用逗号分隔每个字符,如:

[, ', t, h, i, n, g, 1, ', ,,  , ', t, h, i, n, g, 2, ', ,,  , 
', t, h, i, n, g, 3, ', ,,  , ', t, h, i, n, g, 4, ', and ]

当它要求我输入时,我只需要输入相同的列表,比如:['thing1','thing2','thing3','thing4'


Tags: andtheto代码stringlenwithfunction
3条回答

有一个内置的,为你做到这一点!它被称为str.join,您可以在要加入的列表中调用它。你知道吗

>>> some_list = ["foo", "bar", "spam", "eggs"]
>>> ", ".join(some_list)
foo, bar, spam, eggs

但是,这并没有考虑“and”要求。只需重新编写列表的最后一项,就可以相当简单地处理这个问题。你知道吗

>>> some_list = ["foo", "bar", "spam", "eggs"]
>>> some_list[-1] = "and " + some_list[-1]
>>> ", ".join(some_list)
foo, bar, spam, and eggs

将其作为函数写入:

def line_them_up(lst):
    new_lst = lst[:]  # copy the list so we don't change the original
    new_lst[-1] = "and " + new_list[-1]
    return ", ".join(new_lst)

inputsplit获取输入。如果愿意,您甚至可以将strip映射到结果列表上,尽管这不是必需的。你知道吗

user_list = map(str.strip, input("Enter a space-separated list: ").split())

首先,您必须指定用户输入数据的方式。如果希望输入的单词在一行中用空格隔开,可以使用以下代码:

spam = input().split() 

如果要在每个输入单词后按Enter键,可以使用以下代码:

spam=[]
while l != '':
l = input().rstrip()
spam.append(l)

否则:你可以创造你自己的方式

我想这就是你想要的:

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

def printTogether(aList):
    result = ""
    for i in range(len(aList)):
        if i == 0:
            result = result + aList[i]
        elif i == (len(aList)-1):
            result = result + " and " + aList[i]
        else:
            result = result + ", " + aList[i]
    print(result)

printTogether(spam)

任务描述有点误导,但从他们提供的示例来看,这就是我认为他们想要的

相关问题 更多 >

    热门问题