我正在编写一个代码,程序从文件中读取数据,然后读取数据,如果列表中存在特定的单词,则允许用户修改其数量。那么问题是如何在for循环搜索单词时获取for循环中的迭代次数(行号)
我的代码:
f= open('guru99.txt','r')
action = int(input('Enter number'))
if action == 1:
for line in lines:
if 'banana' in line:
print(line)
print('You already purchased banana! You can change the quantity')
edit = line.split()
qty = int(input('Enter new quanity'))
print(bline)
else:
continue
例如,如果在第3行找到 banana 这个词。如何编辑此程序以显示for循环的迭代编号或索引
答案 0 :(得分:1)
添加一个跟踪当前传递的迭代次数的变量:
f= open('guru99.txt','r')
lines = f.readlines()
i =1
for line in lines:
print([i],line)
i = i+1
count = 0
action = int(input('Enter line number'))
if action == 1:
for line in lines:
count += 1
print(count)
if 'banana' in line:
print(line)
print('You already purchased banana! You can change the quantity')
edit = line.split()
qty = int(input('Enter new quanity'))
edit[-1] = (int(edit[-1]) / float(edit[3]))
bprice = (edit[-1])
edit[3] = str(qty)
edit[-1] = str(int(qty * bprice))
bline = ' '.join(edit)
print(bline)
else:
continue
答案 1 :(得分:0)
f= open('guru99.txt','r')
lines = f.readlines()
i =1
line_counter = 0
for line in lines:
print([i],line)
i = i+1
action = int(input('Enter line number'))
if action == 1:
for line in lines:
line_counter += 1
if 'banana' in line:
print('You are on line: ' + str(line_counter)
print('You already purchased banana! You can change the quantity')
edit = line.split()
qty = int(input('Enter new quanity'))
edit[-1] = (int(edit[-1]) / float(edit[3]))
bprice = (edit[-1])
edit[3] = str(qty)
edit[-1] = str(int(qty * bprice))
bline = ' '.join(edit)
print(bline)
else:
continue
答案 2 :(得分:-1)
您可以尝试使用while循环替换它:
i = 0
while i < len(lines):
# Your code here
i = i + 1
i
等于迭代,lines[i]
等于当前行。