【问题标题】:How to order a list according to specific order?如何根据特定顺序对列表进行排序?
【发布时间】:2019-10-17 07:50:53
【问题描述】:

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

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    如果你想按bigram中每个项目的前两个单词的位置对bigram_info进行排序,你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 2015-09-25
      相关资源
      最近更新 更多