-1
myFile = open("task3.txt","r")
myList = myFile.readlines()
word = myList[0].split(' ')
position = [0]
for count, i in enumerate(word):
if word.count(i) < 2:
position.append(count+1)
else:
position.append(word.index(i)+1)
position.remove(0)
print(position)
recreate= []
for count in position:
recreate.append(word[count-1])
print(recreate)
with open ("test.txt","w") as file:
file.write(" ".join(recreate))
这里我的代码应该拆分读取文件到单词和位置,并利用这些来做到这一点正确地重新句话在新file.It,但是当我打印的位置,他们都错了:当我的代码输出时,为什么位置错误?
这是正确的位置:[1,2,3,4,5,5,4,3,6,7,8]
task3.txt =一,二,三,四,五,五,四,三,二和一。
,这是被印刷的内容:[1,2,3,4,5,5,4,3,9,10,11]
的test.txt =一个,两个,三个,四个,五,五,四,三,二和一。
谢谢。
为什么是正确的输出?什么是输入? –
由于位置对应于列表中每个单词的索引:“two = index(8)+ 1 = 9”和“index(9)+ 1 = 10”,所以位置看起来不错,一个指数=(10)+ 1 = 11'。不知道为什么'6,7,8'是正确的位置。 – davedwards