如何替换列表中的元素?

时间:2018-12-22 16:23:04

标签: python-3.x

我不太确定如何正确表达我的问题,但我会尽力而为。 我正在上一个课堂项目,一部分正在使用列表。

因此,首先,我在列表中设置随机值。 a = [1,1,1,0,0,0,0]

为了更清楚地说明,我正在制定一个程序来管理电影院的座位安排。 1是空缺,0是空缺。因此,这意味着仅剩4个空位。客户使用该程序,然后程序为客户选择座位,因此选择了第一个零,现在只剩下三个空位。另一个客户使用该程序,直到所有座位都坐满为止,都会发生相同的事情,然后将打印一条声明“所有座位都坐满了”的

我如何做到这一点?

我希望我能够正确地表达这个问题

谢谢!

这就是我尝试过的。 (而且绝对失败了,哈哈):

a = [1, 1, 1, 0, 0, 0, 0]
for i in a:
    if i ==0:
        a[i] = 1

编辑:

while True:
    seats = [1,1,1,0,0,0]
    for i, seat in enumerate(seats):
        if seat == 0:
            seats[i] = 1
            print("Your seat is at", i)
            break  
    else:  
        print("No more seats!")
    user = int(input("Press 1 to reserve another seat, 2 to quit the program"))
    if user == 2:
        break

6 个答案:

答案 0 :(得分:1)

根据问题类型进行猜测,其中一些可能对您来说是新的。但是,我相信看到不同的做事方式总是很高兴的,而且您总是可以查找内容并学习新知识!

您需要检查列表中是否有零,如果找到了零,则将其切换为1。重要的是,您应该停止(break)的查找,因为您不想填全部立刻就座。

像这样的事情是一种可能的写法(同样,有很多方法可以做到这一点,这只是其中之一)。无论您想坐多少人,仍然需要重复此过程。

for i, seat in enumerate(seats):
    if seat == 0:
        seats[i] = 1
        print("Your seat is at", i)
        break  # Stop looking for seats.
else:  # If no break happened. 
    print("No more seats!")

答案 1 :(得分:1)

a[a.index(0)] = 1将用1替换找到的第一个零,如果没有更多零,则引发异常。您可以捕获到异常:

try:
    a[a.index(0)] = 1
except ValueError:
    print('no more seats')

答案 2 :(得分:0)

您的代码段会将第一个元素设置为1,如果它是0。您需要一种方法来找到第一个元素的索引0,并将其设置为1

尝试使用index函数来获取一个元素的索引并使用该索引...或者只是将总的和当前占用的座位数保存为数字。

答案 3 :(得分:0)

在检查数组内容时,为什么将i与0进行比较:

a = [1, 1, 1, 0, 0, 0, 0]
for i, val in enumerate(a):
    if val == 0:
        a[i] = 1

答案 4 :(得分:0)

           a =[1,1,1,0,0,0]
           for x in sorted(a):
             if len(a) == sum(a):
               print('seats are full ')
             else:   
                 a[x].pop
                 a.append(1)
                 print ('your  seat is at a[x]')

答案 5 :(得分:0)

好的,因此,我使用forwhile循环为您的问题提供了两种解决方案。我个人认为,在这种情况下,使用while循环更可取,以避免使用break命令。

def original_main():
    a = [1, 1, 1, 0, 0, 0, 0]
    for i in a:
        # i here will be equal to the values in the list, what happens here is that the value is being copied to a new paramater.
        if i == 0:
            a[i] = 1

    print('original_main:', a)


def fixed_main():
    a = [1, 1, 1, 0, 0, 0, 0]

    for index, value in enumerate(a):
        # What happens here is that enumerate takes both the index and value of the element and uses them.
        # You check whether the value of the seat is 0, AKA free.
        if value == 0:
            # You update the location of the same element/ seat to being occupied.
            a[index] = 1
            # To stop the loop, often preferable not to need to use breaks.
            break
    print('fixed_main:', a)


def alternative_main():
    a = [1, 1, 1, 0, 0, 0, 0]
    index = 0
    # Cycle through the list until reaching the end of the list or the seat is free.
    while index < len(a) and a[index] != 0:
        index += 1

    # Check whether there were any empty seats as if there weren't index will be higher or equal to the amount of seats.
    # Thechnically it can only be equal due to the while condition but it is a better practice to cover all scenarios.
    if index >= len(a):
        print('No empty seats.')
    else:
        a[index] = 1

    print('alternative_main:', a)


if __name__ == '__main__':
    original_main()
    print()
    fixed_main()
    alternative_main()

打印结果:

original_main: [1, 1, 1, 0, 0, 0, 0]

fixed_main: [1, 1, 1, 1, 0, 0, 0]
alternative_main: [1, 1, 1, 1, 0, 0, 0]