我有一些包含在元组列表中的数据。如果另一部分满足某些条件,我想总结每个元组的一部分。以下是一些示例数据:
var = [("car", '1'), ("dog", '1'), ("mercedes", '1'), ("cat", '1'), ("ferrari", '1'), ("bird", '1')]
我有以下代码,允许我访问上述结构中的所有数字数据:
var = [x[1] for x in var]
print ",".join(map(lambda x: str(x).strip(), var))
这将按以下格式打印出数据:
1,1,1,1,1,1
如果我在列表推导中使用x[0]
,我会得到一个输出:
car, dog, mercedes, cat, ferrari, bird
我想要的是:
if x[0] == "car" or x[0] == "mercedes" or x[0] == "ferrari" then var2 == x[1] + x[1] + x[1]
print var2
我假设上面的内容不起作用,但我不确定如何以一种可行的方式对其进行编码。
以上是一个简单的演示。我正在解析的完整字符串是:
[("'goal','corner','rightfoot'", '1'), ("'goal','directfreekick','leftfoot'", '1'),
("'goal','openplay','leftfoot'", '1'), ("'goal','openplay','rightfoot'", '2'),
("'miss','corner','header'", '3'), ("'miss','directfreekick','leftfoot'", '1'),
("'miss','directfreekick','rightfoot'", '1'), ("'miss','openplay','header'", '3'),
("'miss','openplay','leftfoot'", '8'), ("'miss','openplay','rightfoot'", '11')]
...我用来解析的确切语法是:
matching = {"'goal','openplay','leftfoot'", "'goal','openplay','rightfoot'", "'goal','corner','leftfoot'", "'goal','corner','rightfoot'"}
regex2 = [value for key, value in regex2 if key in matching]
regex2 = sum(int(value) for key, value in regex2 if key in matching)
print regex2
...其中为regex2分配了上面元组列表的值。求和线是导致错误的行。它上面的行打印如下:
['1', '1', '2']
答案 0 :(得分:3)
将sum()
与生成器表达式一起使用,测试您的条件:
matching = {'car', 'mercedes', 'ferrari'}
sum(int(value) for key, value in var if key in matching)
生成器表达式与列表理解功能大致相同;遍历列表并对每个元素执行某些操作。我选择在循环中使用元组赋值;每个元组中的两个元素分别分配给key
和value
。然后,我们可以使用if
语句进行过滤(如果key
值是matching
集的成员),并且只使用总和中的value
部分。
快速演示,向您展示会发生什么,包括列表理解版本,以显示只选择了一部分值:
>>> var = [("car", '1'), ("dog", '1'), ("mercedes", '1'), ("cat", '1'), ("ferrari", '1'), ("bird", '1')]
>>> matching = {'car', 'mercedes', 'ferrari'}
>>> [value for key, value in var if key in matching]
['1', '1', '1']
>>> sum(int(value) for key, value in var if key in matching)
3
当然,当您使用'1'
以外的值时,这会变得更有趣:
>>> var = [("car", '8'), ("dog", '2'), ("mercedes", '16'), ("cat", '4'), ("ferrari", '32'), ("bird", '64')]
>>> [value for key, value in var if key in matching]
['8', '16', '32']
>>> sum(int(value) for key, value in var if key in matching)
56
至于您尝试实施我的解决方案,您将原始列表替换为仅包含 值的列表。删除列表理解行重新绑定regex2
并运行 sum()
行:
>>> regex2 = [("'goal','corner','rightfoot'", '1'), ("'goal','directfreekick','leftfoot'", '1'),
... ("'goal','openplay','leftfoot'", '1'), ("'goal','openplay','rightfoot'", '2'),
... ("'miss','corner','header'", '3'), ("'miss','directfreekick','leftfoot'", '1'),
... ("'miss','directfreekick','rightfoot'", '1'), ("'miss','openplay','header'", '3'),
... ("'miss','openplay','leftfoot'", '8'), ("'miss','openplay','rightfoot'", '11')]
>>> matching = {"'goal','openplay','leftfoot'", "'goal','openplay','rightfoot'", "'goal','corner','leftfoot'", "'goal','corner','rightfoot'"}
>>> sum(int(value) for key, value in regex2 if key in matching)
4