以下是我的尝试:
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]
,但我的输出是完全错误的。
我该怎么做?
答案 0 :(得分:1)
您可以像这样使用map
和intersection
:
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)
您没有在代码中正确累积结果。每次迭代都要开始计算,最后会附加结果。
for i in my_tickets
遍历门票本身,而不是其索引。
这是固定代码:
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
现在,通过展平你的循环可以使这更漂亮:
此if语句
if number == x:
result += 1
可以使用True
被解释为1:
result += (number==x)
这个
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
。
现在,我们有了这个
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]
因此,您的整个代码可以是一行代码:
def lotto_matches(xs, my_tickets):
return [sum(x in ticket for x in xs) for ticket in my_tickets]