[英]Retrieving list item values
I've been trying to code a seat booking program which does the following: 我一直在尝试编写执行以下操作的座位预订程序:
Everything works as it should however I'm struggling with retrieving the seat numbers of the free seats. 一切正常,但是我正在努力获取免费座位的座位号。 Any ideas with my current method? 我目前的方法有什么想法吗? Much appreciated! 非常感激!
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 structure 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
Here is one alternate way to go about this: 这是解决此问题的另一种方法:
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
Your specification (as written) does not require us to tell the user how many seats actually are available in the row if it is not enough for their needs. 您的说明(按书面规定)不需要我们告诉用户该行中实际有多少座位可用,如果这不足以满足他们的需求。
(Using line E
in this case) (在这种情况下,使用E
行)
This 这个
>>> groups = [(k, len(list(g))) for k, g in groupby(line)]
>>> groups
[('1', 1), ('0', 1), ('1', 1), ('0', 7)]
Gives you the mapping of the number of occupied/free consecutive rows 为您提供已占用/空闲连续行数的映射
Then, 然后,
>>> [i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq]
[3]
Gives you all the indices of the blocks that have sufficient space 给您所有具有足够空间的块的索引
Or, blockIndex = next((i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq), None)
returns the first matching block or None
或者, blockIndex = next((i for i, x in enumerate(groups) if x[0] == '0' and x[1] > SpacesReq), None)
返回第一个匹配块或None
Then, 然后,
>>> sum(blockSize for _, blockSize in groups[:blockIndex])
3
Gives you the total number of seat before your large enough block. 为您提供足够大的座位之前的总座位数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.