我有一個物件串列“repeated_words_list”,每個物件都包含一個字典,其中包含一個單詞(字串)、開始(浮動)、結束(浮動)、conf(浮動)
我想在所有重復單詞中只保留 1 次具有最高 p.start 的重復單詞,并洗掉所有 p.start 較低的重復單詞。
我已經這樣列印了
for p in repeated_words_list:
print(f"{p.word} {p.start} - {p.end}")
輸出
p.word p.start - p.end
the 0.27 - 2.91
the 25.38 - 25.5
the 26.94 - 27.24
the 27.66 - 27.81
the 38.67 - 38.705229
the 53.22 - 53.73
the 55.02 - 55.17
well 2.91 - 3.39
well 3.96 - 4.38
well 5.82 - 6.09
well 9.09 - 9.42
well 12.21 - 12.63
keeping 4.53 - 4.95
keeping 13.2 - 13.53
yourself 4.95 - 5.43
yourself 13.53 - 14.04
it 6.09 - 6.24
it 56.67 - 56.88
can 6.24 - 6.57
can 21.09 - 21.48
is 15.81 - 16.05
is 25.86 - 26.04
is 28.14 - 28.26
a 16.05 - 16.14
a 22.862336 - 22.89
see 54.764476 - 55.02
whether 61.35 - 61.71
whether 63.63 - 63.93
it's 61.71 - 62.07
it's 63.93 - 64.17
我嘗試過這種方式,但無法完成,因為我無法訪問上一個和下一個元素。
for i in range(len(repeated_words_list)):
if p[i].word == p[i-1].word:
if p[i].start > p[i-1].start:
repeated_words_list[i-1]= p[i].start
一些好的靈魂可以指導我嗎?提前致謝!
uj5u.com熱心網友回復:
創建一個word用作索引的字典。如果索引已存在,則僅在找到更高值時才更新該值start。
final_words = {}
for p in repeated_words_list:
word = final_words.get(p.word, None)
if not word:
final_words[p.word] = p
else:
if word.start < p.start:
final_words[p.word] = p
# to get highest values
for p in final_words.values():
print(f"{p.word} {p.start} - {p.end}")
# for all words other than the one with highest occurence
for p in repeated_words_list:
if final_words[p.word] != p:
print(f"{p.word} {p.start} - {p.end}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439270.html
