【问题标题】:Matching each element in a list to each element in a list of a list, using Python使用 Python 将列表中的每个元素与列表中的每个元素进行匹配
【发布时间】:2018-09-05 14:00:11
【问题描述】:

我正在尝试找到使用 Python 将列表中的每个元素与列表列表中的每个元素匹配的最有效方法。例如输入:

>>>myList = [['hi', 'no', 'bye', 'Global', 24],['morning', 'X', 'place'],['so', 'large', 'mall','test'], ['hi', 'X', 'place', 'bye']]
>>>check_against_myLIst = ['bye','place','hi','australia']

现在我不确定最好的方法是使用 map 函数、for 循环还是任何其他 python 数据分析方法。

输出需要转换成数据帧,输出就是这样。

Index   Value                                      Result
0       ['hi', 'no', 'bye', 'Global', 24]          True
1       ['morning', 'X', 'place']                  True
2       ['so', 'large', 'mall','test']             False
3       ['hi', 'X', 'place', 'bye']                True

谢谢!

【问题讨论】:

  • 永远不要给你的变量命名为python的内置函数。
  • 我认为您可能对元组和列表有些混淆...
  • 为什么索引 3 的结果为 True?
  • @timgeb 因为索引 3 的值包含“hi”和“bye”。要使其为真,该值必须包含存在于 check_against_myList 中的元素
  • @helloWorld 好的。下次请在问题中添加您想要做什么的说明。

标签: python list data-analysis


【解决方案1】:

您可以将结果存储在列表中并从中构造一个数据框

result = [False]*len(myList)
for n, _list in enumerate(myList):
    if [i for i in _list if i in check_against_myLIst]:
        result[n] = True

【讨论】:

  • 这会产生 [True, True, True, True] 但 OP 有 [True, True, False, True]。您可能是正确的,因为我对 OP 与什么匹配感到困惑。
  • 我在 OP 中犯了一个错误,现在已经修复它,所以现在应该输出 [True, True, False, True]。
【解决方案2】:

首先,从 myList 创建集合,用于 O(1) 成员资格测试。

>>> myList = [['hi', 'no', 'bye', 'Global', 24],['morning', 'X', 'place'],['so', 'large', 'mall','test'], ['hi', 'X', 'place', 'bye']]
>>> checks = ['bye','place','hi','australia'] # renamed from check_against_myLIst
>>> sets = map(set, myList)

使用高效的any 检查来确定checks 的任何元素是否在给定集合中。 (与计算交叉点相反,any 是惰性的。)

>>> result = [(lst, any(s in set_ for s in check)) for lst, set_ in zip(myList, sets)]

构建数据框。

>>> df = pd.DataFrame(result, columns=['Value', 'Result'])
>>> df.index.name = 'Index'
df

                           Value  Result
Index                                   
0      [hi, no, bye, Global, 24]    True
1            [morning, X, place]    True
2        [so, large, mall, test]   False
3            [hi, X, place, bye]    True

【讨论】:

    【解决方案3】:

    这里有关于不使用 pandas 即可获得它的示例。 无论如何,让我解释另一个观点:

    # list
    my_list = (['hi', 'no', 'bye', 'Global', 24],['morning', 'X', 'place'],['so', 'large', 'mall','test','TESSTTTT'], ['hi', 'X', 'place', 'bye'])
    
    # check list
    check_against_myLIst = ('bye','place','hi','australia')
    
    # Function to find intersection of two arrays
    def interSection(index, arr1,arr2):
        result = 'false'
        output = list(filter(lambda x: x in arr1, arr2))
        if output:
            result = 'true'
    
        print 'index',"\t"*1,'Value',"\t"*6,'Result'
        print index,"\t"*1,arr1,"\t"*4,result
        print  ''
    
    # Driver program
    if __name__ == "__main__":
        count = 0
        for arrayItem in my_list:
            interSection(count, arrayItem,check_against_myLIst)
            count += 1
    

    【讨论】:

      【解决方案4】:

      您可以创建一个函数来测试列表集和比较列表之间的交集。

      给定

      import pandas as pd
      
      
      cmp = ["bye","place","hi","australia"]
      lst = [
          ["hi", "no", "bye", "Global", 24],
          ["morning", "X", "place"],
          ["so", "large", "mall","test"], 
          ["hi", "X", "place", "bye"]
      ]
      

      代码

      def is_in(nested, compare):
          """Return a tuple of (row, bool), True if the compared list intersects."""
          compared = set(compare)
          return [(x, bool(set(x) & compared)) for x in nested]
      

      bool_lst = is_in(lst, cmp)
      bool_lst
      

      输出

      [(['hi', 'no', 'bye', 'Global', 24], True),
       (['morning', 'X', 'place'], True),
       (['so', 'large', 'mall', 'test'], False),
       (['hi', 'X', 'place', 'bye'], True)]
      

      它看起来与您的输出相似。从这里开始,我们只需要制作一个 DataFrame:

      df = pd.DataFrame(bool_lst, columns=["Value", "Result"])
      df.rename_axis("Index")
      

      输出

      后者都可以简化为一行:

      pd.DataFrame([(x, bool(set(x) & set(cmp))) for x in lst], columns=["Value", "Result"]).rename_axis("Index")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2013-06-06
        • 2015-04-02
        • 2017-10-30
        • 2015-08-18
        相关资源
        最近更新 更多