我有两个列表:
bigrams = ['apple pie', 'red vine', 'chicken salad']
bigram_info = ['red vine 1', 'apple pie 0', 'chicken salad 2']
我想根据bigrams列表订购bigram_info列表:
ordered_list = ['apple pie 0', 'red vine 1', 'chicken salad 2']
我尝试了一些操作,但是由于列表很大,所以没有得到正确的结果。
``` file=open("bigrams.txt","r")
bigrams = file.read().splitlines()
file.close()
#print(bigrams)
with open("bigram_info.txt", "r") as my_file:
for line in my_file:
words = line.split()
words[0 : 2] = [' '.join(words[0 : 2])]
for w in bigrams:
if w==words[0]:
print(line)
When I run the code it prints that elements in order of bigram_info list.Like
``` bigram_info = ['red vine 1', 'apple pie 0', 'chicken salad 2']```
答案 0 :(得分:0)
如果要按bigram_info
中每个项目的前两个单词的位置对bigram
进行排序,可以使用以下方法:
sorted(bigram_info, key=lambda x: bigrams.index(' '.join(x.split()[:2])))