简体   繁体   English

我如何在 Python 中请求一个集合列表,请求一个数字 (x),删除 x 个输入,然后重新列出它们?

[英]How do I ask for a set list in Python, ask for a number (x), remove x number of inputs, and re-list those?

I am new to Python, and I am currently learning about lists.我是 Python 新手,目前正在学习列表。 This is the question that I am trying to solve:这是我试图解决的问题:

Your favourite band is in town, and tickets are selling fast!你最喜欢的乐队在城里,门票卖得很快! Alas, you were too late to snag one, so you put your name in the waitlist, in case any extra tickets are released.唉,你来不及抢到一张,所以你把你的名字放在候补名单中,以防任何额外的票被释放。

Write a program to manage the waitlist for the concert.编写一个程序来管理音乐会的候补名单。

Your program should read in a list of the names in the waitlist, and the number of extra tickets released.您的程序应读取候补名单中的姓名列表,以及已发放的额外门票数量。

Then, it should announce the names of people who score the extra tickets.然后,它应该公布获得额外门票的人的名字。

Here's an example of how your program should work:以下是您的程序应该如何工作的示例:

 People in line: Dave, Lin, Toni, Markhela, Ravi Number of extra tickets: 3 Tickets released for: Dave, Lin, Toni

Note: The names are separated by a comma and a space (', ').注意:名称由逗号和空格 (', ') 分隔。

If there are no more tickets released, your program should work like this:如果没有更多门票发布,您的程序应该像这样工作:

 People in line: Mali, Micha, Mary, Monica Number of extra tickets: 0 Fully Booked!

This band is so popular that there will always be at least as many people as extra tickets.这个乐队非常受欢迎,总有至少和额外门票一样多的人。 You won't have to worry about index errors.您不必担心索引错误。

I have tried the following, but it always prints the entire list, not just a subset.我尝试了以下方法,但它总是打印整个列表,而不仅仅是一个子集。

ppl = []
sep = ', '
ppl_in_line = input('People in line: ')
ppl.append(ppl_in_line)
x = int(input('Number of extra tickets: '))
if x == 0:
    print('Fully Booked!')
else:    
    y = ppl[:x]
    print('Tickets released for: ' + (sep.join(y)))

ppl_in_line is a string. ppl_in_line 是一个字符串。 So when you append to ppl, you are appending a single string.因此,当您附加到 ppl 时,您将附加一个字符串。

To enter a separated list of ppl on a single line do this:要在一行中输入一个单独的 ppl 列表,请执行以下操作:

ppl_in_line = input('People in line: ').split(sep)

You forgot to split your people in line into multiple elements:您忘记将您的人员分成多个元素:

ppl_in_line = input('People in line: ')
ppl = ppl_in_line.split(sep)

This is assuming that your input for People in line: is something like这是假设您对People in line:输入类似于

Dave, Lin, Toni, Markhela, Ravi

If you want to use ppl.append , you have to mention them name by name in a loop:如果您想使用ppl.append ,您必须在循环中按名称提及它们:

while True:
    ppl_in_line = input('People in line: ')
    if not ppl_in_line:
        break
    ppl.append(ppl_in_line)

You can enter the names like您可以输入名称,如

Dave
Lin
Toni
Markhela
Ravi

An empty input will finish the list.空输入将完成列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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