簡體   English   中英

檢索列表項值

[英]Retrieving list item values

我一直在嘗試編寫執行以下操作的座位預訂程序:

  • 接受用戶輸入(行,座位數)
  • 根據上述輸入,檢查外部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

這是解決此問題的另一種方法:

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

您的說明(按書面規定)不需要我們告訴用戶該行中實際有多少座位可用,如果這不足以滿足他們的需求。

(在這種情況下,使用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

為您提供足夠大的座位之前的總座位數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM