简体   繁体   中英

Print a list of items separated by commas but with the word “and” before the last item

I've been working on this for two days. This is what the assignment states:

Say you have a list value like this: listToPrint = ['apples', 'bananas', 'tofu', 'cats'] Write a program that prints a list with all the items separated by a comma and a space, with "and" inserted before the last item. For example, the above list would print 'apples, bananas, tofu, and cats' . But your program should be able to work with any list not just the one shown above. Because of this, you will need to use a loop in case the list to print is shorter or longer than the above list.

This is what I have thus far:

listToPrint = []
while True:
    newWord = input("a, b, and c ")
    if newWord == "":
        break
    else:
        listToPrint.append(newWord)

The code you've shown appears to be solving a different problem than what your assignment wants you to do. The assignment is focused on print ing the values from a provided list , while your code is all about input ing items from the user and putting them into a list. It could make sense to do one and then the other, but for the assignment that you've given in the comments, the input code is completely irrelevant.

Here's how I'd solve that assignment (probably with code that you don't understand yet):

print("{}, and {}".format(", ".join(list_to_print[:-1]), list_to_print[-1]))

A more "novice friendly" approach would look more like this:

for item in list_to_print[:-1]:
    print(item, end=', ')
print('and', list_to_print[-1])

Here is how I would do it, but be careful if this is for school. Your instructor will frown on you if any of the things I have done below are using features or techniques that haven't yet been covered.

listToPrint = ['a', 'b', 'c']

def list_to_string(L, sep = '', last_sep = None):
    if last _sep is None:
        return sep.join(L)
    else:
        return sep.join(L[:-1]) + last_sep + L[-1]

print(list_to_string(listToPrint, sep = ', ', last_sep = ', and '))

Here's a bit more of a beginner version:

listToPrint = ['a', 'b', 'c']
list_length = len(listToPrint)

result = ""
count = 0
for item in listToPrint:
    count = count + 1
    if count == list_length:
        result = result + "and " + item
    else:
        result = result + item + ", "

This one doesn't work with only one item in the list.

Beginner Version:

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

print("'", end='')

for i in range(len(x)-2):

    print(x[i], end=', ')

print(str(x[-2])+' and '+str(x[-1]),end='')

print("'")

Output: 'apples, bananas, tofu and cats'

#printing the first element sep. so the list works     
print(listToPrint[0], end="") 

for i in range(1, len(listToPrint)-1):

    print("," + listToPrint[i], end="") #this prints the middle elements

if(len(listToPrint) > 1):

    print( " and " + listToPrint[-1], end="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM