gpt4 book ai didi

python - 当我只需要向用户添加的行时,为什么它会在 nlist 中记录额外的项目/行( ' ' )?

转载 作者:行者123 更新时间:2023-11-30 22:05:20 25 4
gpt4 key购买 nike

示例:我输入正数:1、2、3、4,然后输入 -1 结束第一个函数。第二个函数中显示的列表(nlist)为['1', '2', '3', '4', '']。这个额外的第五项从哪里来?我该如何防止它?

def pos_num():

# Open num.txt and define num
num_list = open('num.txt', 'w')
num = 1

# While num is positive, ask user for input
while num >= 0:
num = int(input('Type + number to add to num_list, - number to end: '))

# If user input is positive: \
# convert to str, add to list, convert to int to continue loop
if num >= 0:
num = str(num)
num_list.write(num + '\n')
num = int(num)

# If user input is negative: \
# close num.txt and inform user
else:
num_list.close()
print('List has been written to num.txt')

# Call program 1
pos_num()

# Program 2: Number File Reader
def nfread():

# Ask user for filename to open
filename = input('Filename: ')
infile = open(filename, 'r')

# Create empty list
nlist = []

# Read first line, strip '\n', append to nlist, begin line count
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count = 1

# While line is not empty: \
# read line, strip '\n', append line to nlist, add 1 to count
while line != '':
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count += 1
print(line, count)

# Close num.txt
infile.close()

# Return nlist
return nlist

最佳答案

考虑更改此 block :

# Read first line, strip '\n', append to nlist, begin line count
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count = 1

# While line is not empty: \
# read line, strip '\n', append line to nlist, add 1 to count
while line != '':
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count += 1
print(line, count)

类似的事情

count = 0
for line in infile:
line = line.rstrip()
if line:
nlist.append(line)
count += 1
print(line, count)

在所有更改中,应该修复您的程序的更改是添加 if line: ——它将导致您的程序向您的程序附加一个空元素。列表(仅对换行符调用 .rstrip() 的结果)。

关于python - 当我只需要向用户添加的行时,为什么它会在 nlist 中记录额外的项目/行( ' ' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com