如何根据特定顺序订购清单?

时间:2019-10-17 07:50:53

标签: python-3.x

我有两个列表:     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']```

1 个答案:

答案 0 :(得分:0)

如果要按bigram_info中每个项目的前两个单词的位置对bigram进行排序,可以使用以下方法:

sorted(bigram_info, key=lambda x: bigrams.index(' '.join(x.split()[:2])))