将列表列表与列表进行比较以查找相似的数字

时间:2014-02-06 00:06:30

标签: python list function for-loop nested

以下是我的尝试:

my_tickets = [ [ 7, 17, 37, 19, 23, 43],
           [ 7, 2, 13, 41, 31, 43],
           [ 2, 5, 7, 11, 13, 17],
           [13, 17, 37, 19, 23, 43] ]

def lotto_matches(xs, my_tickets):
   xi = 0 # could be used to pick specific things from lists
   yi = 0 # could be used to pick specific things from lists
   result = []
   for i in my_tickets: # List of lists
      for x in xs: # Picks
         if my_tickets[i] == xs[x]: #Not sure what my if statement is suppose to be
            result.append() # I don't know what goes in the parenthesis
    print (result)
    return (result)

lotto_matches([42,4,7,11,1,13], my_tickets)

我正在尝试编写一个能够获取故障单和平局列表的函数,并返回一个列表,告诉每张故障单上有多少选择。

它应该返回[1,2,3,1],但我的输出是完全错误的。

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以像这样使用mapintersection

def lotto_matches(pick, my_tickets):
    result = map(lambda x: len(set(x).intersection(pick)), my_tickets)
    return result

print lotto_matches([42,4,7,11,1,13], my_tickets)

其中pick是您要匹配的门票。

如果您使用的是Python 3,map会返回迭代器,这可能不是您想要的,所以您需要

return list(result)

答案 1 :(得分:1)

创建套装的开销几乎不值得,除非你的抽签有更多的球。

def lotto_matches(xs, my_tickets):
    xs = set(xs) # optional - may not be any faster if xs is a small list
    return [sum(x in xs for x in t) for t in my_tickets]

答案 2 :(得分:0)

如果你需要一个班轮:

output = [len(list(set(a_list) & set(draw))) for a_list in my_tickets]

答案 3 :(得分:0)

  1. 您没有在代码中正确累积结果。每次迭代都要开始计算,最后会附加结果。

  2. for i in my_tickets遍历门票本身,而不是其索引。

  3. 这是固定代码:

    def lotto_matches(xs, my_tickets):
        results = []
        for ticket in my_tickets:
            result = 0
            for number in ticket:
                for x in xs: 
                    if number == x: 
                        result += 1
            results.append(result)
        return result
    

    现在,通过展平你的循环可以使这更漂亮:

    1. 此if语句

      if number == x: 
          result += 1
      

      可以使用True被解释为1:

      的事实
      result += (number==x)
      
    2. 这个

      result = 0
      for number in ticket:
          for x in xs: 
              result += (number==x)
      

      是使用嵌套循环计算的总和,可以将其转换为此

      result = sum(number==x for number in ticket for x in xs)
      

      这是检查x中存在的所有ticket值,可以使用in进行简化(同样,x in ticket将返回True }(1)x中存在ticket时:

      result = sum(x in ticket for x in xs)
      

      也就是说,如果x中存在来自xs的{​​{1}},我们希望在总和中添加一个ticket

    3. 现在,我们有了这个

      results = []
      for ticket in my_tickets:
          result = sum(x in ticket for x in xs)
          results.append(result)
      

      相当于

      results = [sum(x in ticket for x in xs) for ticket in my_tickets]
      
    4. 因此,您的整个代码可以是一行代码:

      def lotto_matches(xs, my_tickets):
          return [sum(x in ticket for x in xs) for ticket in my_tickets]