简体   繁体   English

如果在使用lambda,map和list时Boolean为True,如何返回以下位置的列表?

[英]How to return a list of the following position if Boolean is True while using lambda, map, and list?

I have a list of names and after each name is a number. 我有一个名字列表,每个名字后面都有一个数字。 Like this 像这样

l = ["Bob", 4, "Rob", 5, "Sam", 6, "Bob", 5]

I would like to return a list of numbers that correspond to a given name, by only using lambda, map, list or filter. 我想仅通过使用lambda,map,list或filter来返回与给定名称相对应的数字列表。

For example, if I were to use the name Bob with list = ["Bob",4,"Rob",5,"Sam",6,"Bob",5] , my output would be 例如,如果我要使用名称Bob以及list = ["Bob",4,"Rob",5,"Sam",6,"Bob",5] ,我的输出将是

[4,5]

I think I understand most of lambda, I just can't get it to return what I want it too. 我想我了解大多数lambda,但我也无法让它返回我想要的东西。

mx = list(map(lambda x: l[x+1] if x == name, l))

I am getting this error. 我收到此错误。 Syntax Error: invalid syntax: <string>, line 14, pos 29

You can run through values at even indexes and output the value at the next index when it matches the name: 您可以在偶数索引处遍历值,并在与名称匹配的下一个索引处输出值:

result = [l[i+1] for i in range(0,len(l),2) if l[i] == "Bob"]

If you're allowed to use enumerate, this can be a bit more concise (assuming none of the odd indexes contain a matching string): 如果允许使用枚举,则可以更简洁一些(假设所有奇数索引都不包含匹配的字符串):

result = [l[i+1] for i,n in enumerate(l) if n == 'Bob' ]

or using zip() 或使用zip()

result = [v for n,v in zip(l,l[1:]) if n == 'Bob']

Reconstruct the list into a list of tuples; 将列表重构为元组列表; then a list comprehension is trivial: 那么列表理解是微不足道的:

items = [number for (name, number) in zip(l[0::2], l[1::2]) if name == "Bob"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM