我需要能够打印一个列表,其中我将列表中的所需值标记为“ XX ”,即从“XX”开始。我的问题是我使用了一个嵌套列表并且不知道我应该如何定位某个值。我也不知道我是否能够将整数更改为字符串,或者这是否会弄乱整个列表的打印方式。我的“标记”值的函数如下所示:
i = 0
while i <= len(chosenseat):
findseat = field.index(chosenseat[i])
field[findseat] = "*"+chosenseat[i]+"*"
for idx, row in enumerate(field):
if idx == floor(len(field) / 2):
print("{:^{}}".format('↓ TYST AVD ↓', (len(row) * 4) - 2))
if idx % 2 == 1:
row = row[::-1]
print(("{:<4}" * len(row)).format(*row))
i += 1
(我在 StackOverflow 上从 Hampus Larsson 那里得到了上面的大部分代码!)
整个程序是一个火车车厢的订票系统,我希望能够在预订后用“**”标记所需的座位。打印列表时,它看起来像:
1 2 3 4
8 7 6 5
9 10 11 12
↓ TYST AVD ↓
16 15 14 13
17 18 19 20
24 23 22 21
然后,如果用户例如想要座位 19 和 20,则列表应打印为:
1 2 3 4
8 7 6 5
9 10 11 12
↓ TYST AVD ↓
16 15 14 13
17 18 *19**20*
24 23 22 21
我遇到的另一个问题是,在解开门票时,应该删除“**”,但我目前甚至无法将星星固定到位。有人能在这方面指导我吗?
我试图了解您的初始列表是什么,假设我做对了,这可能是一个解决方案:
import copy
seatList = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
chosenseat = [11, 12]
def find_in2Dlist(lst, item):
for index, sublist in enumerate(lst):
try:
idx = sublist.index(item)
return [index, idx]
except: continue
return None
def printList(mlist, chosenseat):
i = 0
temp = copy.deepcopy(mlist)
while i < len(chosenseat):
findseat = find_in2Dlist(mlist, chosenseat[i])
if findseat == None:
i += 1
else:
temp[findseat[0]][findseat[1]] = '*' + str(mlist[findseat[0]][findseat[1]]) + '*'
i += 1
for idx, row in enumerate(temp):
if idx == len(temp) // 2:
print("{:^{}}".format('↓ TYST AVD ↓', (len(row) * 4) - 2))
if idx % 2 == 1:
row = row[::-1]
print(("{:<4}" * len(row)).format(*row))
def printInitialList(mlist):
print(mList)
printList(seatList, chosenseat) #=>
# 1 2 3 4
# 8 7 6 5
# 9 10 11 12
# ↓ TYST AVD ↓
# 16 15 14 13
# 17 18 *19**20*
# 24 23 22 21
编辑:因为printList
使用了初始列表的副本,所以这个保持不变并且可以重复使用:
print(seatList) #=>
# 1 2 3 4
# 8 7 6 5
# 9 10 11 12
# ↓ TYST AVD ↓
# 16 15 14 13
# 17 18 19 20
# 24 23 22 21
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句