我有一个文本文件studentlist.txt,内容如下:
studentlist.txt
Sam Vimes
Sam Flynn
Sam Gamgee
Sam Carter
Sam Velo
Sam Victory
Sam Vega
我有一个python程序如下:
usernames = []
for line in open('studentlist.txt'):
count = 1
name = line.lower().split()
surname = name[-1]
username = ''.join(name[0:-1])
username_w_surname = username + surname[0]
username_w_surname_integer = username_w_surname + str(count)
if username not in usernames:
usernames.append(username)
elif username_w_surname not in usernames:
usernames.append(username_w_surname)
else:
count = count + 1
usernames.append(username_w_surname_integer)
for entry in usernames:
print (entry)
哪个输出:
sam
samf
samg
samc
samv
samv1
samv1
当它意图输出以下内容时:
sam
samf
samg
samc
samv
samv1
samv2
输出samv1而不是samv2
我只是不确定如何修改此代码以使其按预期工作。
答案 0 :(得分:4)
usernames = []
count = 1 #put countoutside
for line in open('studentlist.txt'):
name = line.lower().split()
surname = name[-1]
username = ''.join(name[0:-1])
username_w_surname = username + surname[0]
username_w_surname_integer = username_w_surname + str(count)
if username not in usernames:
usernames.append(username)
elif username_w_surname not in usernames:
usernames.append(username_w_surname)
else:
count = count + 1
usernames.append(username_w_surname_integer)
for entry in usernames:
print (entry)
sam
samf
samg
samc
samv
samv1
samv2
答案 1 :(得分:2)
usernames = []
count = 1
for line in open('studentlist.txt'):
name = line.lower().split()
if not name[0] in usernames:
usernames.append(name[0])
elif not name[0] + name[-1][0] in usernames:
usernames.append(name[0] + name[-1][0])
else:
usernames.append(name[0] + name[-1][0] + str(count))
count += 1
for entry in usernames:
print(entry)