检索列表项值

时间:2014-03-19 13:26:11

标签: python python-3.x

我一直在尝试编写一个座位预订程序,该程序执行以下操作:

  • 取得用户输入(行,座位数)
  • 根据以上输入检查外部CSV文件中是否有可用的座位。
  • 如果可用,请返回免费座位数,座位号告诉用户该行没有足够的空间。

一切正常,但我正在努力检索免费座位的座位号码。我当前的方法有什么想法吗?非常感谢!

import csv
from itertools import groupby

LargeBlock = 0

SpacesReq = int(input("How many spaces do you require? (8 Max.) "))
while SpacesReq > 8:
    print("Invalid amount.")
    break
SectionReq = input("What row would you like to check between A-E? (Uppercase required) ")

with open('data.csv', 'rt') as file:

    open_f = csv.reader(file,  delimiter=',')

    for line in open_f:
        if line[10] == SectionReq:

            LargeBlock = max(sum(1 for _ in g) for k, g in groupby(line) if k == '0')

            if SpacesReq > LargeBlock:
                print('There are only ', LargeBlock, ' seats together, available on row ',SectionReq,'.')
            else:
                print('There is room for your booking of ',SpacesReq,' seats on row ',SectionReq,'.')
            break

CSV结构

1   0   1   0   0   0   0   0   0   0   E
0   0   0   0   0   0   0   0   0   0   D
0   0   0   0   0   1   0   0   0   0   C
0   0   0   0   0   0   0   0   1   0   B
0   0   0   0   0   1   1   1   1   1   A

2 个答案:

答案 0 :(得分:0)

以下是另一种解决方法:

for line in open_f:
        if line[10] == SectionReq:

            blockfound = "".join([str(e) for e in line[:-1]]).find("0"*SeatsReq)

            if blockfound is not -1:
                print('There are not enough seats together, available on row ',SectionReq,'.')
            else:
                print('There is room for your booking of ',SpacesReq,' seats on row ',SectionReq,', in seats ',str(blockfound),' through ',str(SeatsReq+blockfound),'.')
            break

您的规范(如书面所示)并不要求我们告诉用户如果该行不足以满足他们的需求,那么该行中实际可用的座位数。

答案 1 :(得分:0)

(在这种情况下使用行E

>>> groups = [(k, len(list(g))) for k, g in groupby(line)]
>>> groups
[('1', 1), ('0', 1), ('1', 1), ('0', 7)]

为您提供已占用/空闲连续行数的映射

然后,

>>> [i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq]
[3]

为您提供具有足够空间的块的所有索引

或者,blockIndex = next((i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq), None)会返回第一个匹配的块或None

然后,

>>> sum(blockSize for _, blockSize in groups[:blockIndex])
3

给你足够大的座位之前的座位总数。