一家巧克力公司决定对当前日期前 30 天以上生产的糖果产品提供折扣。我必须有一个矩阵作为打印结果,其中程序读取 2 个文件,一个是不同尺寸的不同糖果的成本,另一个是提供折扣后的阈值天数。
所以基本上,只要数字低于 30(这是来自 days.txt 的输入),它就应该打印一个 "$"
符号,而只要它大于数字(在我们的例子中是 30),它就应该打印一个 "$"
符号只需在其位置打印空格即可。我们还有一个异常情况,candies.txt 矩阵中包含英文字母,并且由于我们正在寻找数字来检查价格而不是字母,因此它应该在其位置中打印一个 "?"
符号地方,因为它不被识别。
这就是我正在尝试做的事情。
candy = []
with open('demo.txt', 'r') as f:
for line in f:
line = line.strip()
if len(line) > 0:
candy.append(map(int, line.split()))
print(candy, end='')
parsedList=[]
with open("demo.txt","r") as f:
lst=f.read().splitlines()
for i in lst:
parsedList.append(i.split())
with open("days.txt","r") as f:
param = int(f.readline().split("=")[1])
for innerList in parsedList:
for element in innerList:
if element.isdigit():
if int(element)>=param:
print (" ", end='')
else:
print( "$", end='')
else:
print ("?", end='')
print(string, end='')
我的问题是,我试图打印文件 demo.txt,然后让 python 以矩阵形式打印替换值的输出。我的值正在打印,但它们不在矩阵中,也没有打印第一个文本文件。
最佳答案
def repl(ch,threshold):
if ch.isdigit():
if int(ch) < threshold:
return '$'
elif int(ch)> threshold:
return " "
else:
return ch
else:
return '?'
lines = []
with open('data') as f, open("data.txt","r") as f2:
threshold = int(f2.read().split('=')[-1])
for line in f:
line = line.strip()
line = line.split()
line = [repl(ch,threshold) for ch in line]
lines.append(line)
# reset to start of demo.txt
f.seek(0)
for line in f:
print(line)
for line in lines:
print()
for el in line:
print(el,end=" ")
31 32 19 11 15 30 35 37
12 34 39 45 66 78 12 7
76 32 8 2 3 5 18 32 48
99 102 3 46 88 22 25 21
fd zz er 23 44 56 77 99
44 33 22 55 er ee df 22
$ $ $ 30
$ $ $
$ $ $ $ $
$ $ $ $
? ? ? $
$ ? ? ? $
关于python - 使用 python 将文本文件解析为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425393/