[英]Using map and zip to determine if sequential items in list have a difference equal to 1
Python beginner here, looking for some guidance and insight. Python初学者在这里,寻求一些指导和见解。 I have the following code that works in python: 我有以下在python中工作的代码:
z=0
y=0
valid=[]
test = [1,2,1,3,4,4,5,2,6,7]
for i, j in zip(test, test[1:]):
if (j - i) == 1:
z += 1
valid.append(i)
valid.append(j)
else:
y += 1
print("There are " + str(len(test)) + " entries with " + str(z) + " sequential events and " + str(y) + " non-sequentual events")
print(list(valid))
This gives me the output I hope for: 这给了我希望的输出:
There are 10 entries with 4 sequential events and 5 non-sequentual events
[1, 2, 3, 4, 4, 5, 6, 7]
I would prefer to be more Pythonic and I am trying to recreate this with map and zip: 我希望使用Pythonic,并且尝试使用map和zip重新创建它:
map(diff_val(help_here_pls), zip(test, test[1:]))
I know that maps follows "map(function, iterable)". 我知道地图遵循“地图(功能,可迭代)”。 How can I get my map output to match my preferred list of 如何获取地图输出以匹配我的首选列表
[1, 2, 3, 4, 4, 5, 6, 7]
using a function (the help_here_pls"). 使用函数(help_here_pls“)。
I know that: 我知道:
Do I pass a tuple via the function in map? 我是否通过map中的函数传递一个元组? Can a lambda handle this, or do I need to define a separate function? lambda可以处理这个问题吗,还是我需要定义一个单独的函数? Even if I can do that, do I have to unpack the tuple? 即使我可以做到,我也必须拆开元组的包装吗? (i ,j) = [passed tuple] (i,j)= [通过的元组]
Thanks in advance for any guidance you can provide! 在此先感谢您提供的任何指导! reading / references welcomed! 欢迎阅读/参考!
A list comprehension is the pythonic choice here. 列表理解是这里的pythonic选择。 I changed the result to give a list of tuples because the flattened list obscured that there is a relationship between each pair of items. 我将结果更改为一个元组列表,因为扁平化的列表模糊了每对项目之间存在关系。
test = [1,2,1,3,4,4,5,2,6,7]
valid = [(i,j) for (i,j) in zip(test, test[1:]) if j-i == 1]
s = "There are {} entries with {} sequential events and {} non-sequentual events"
print(s.format(len(test), len(valid), len(test)-1-len(valid)))
print(valid)
Output: 输出:
There are 10 entries with 4 sequential events and 5 non-sequentual events
[(1, 2), (3, 4), (4, 5), (6, 7)]
Here's another way using more_itertools
: 这是使用more_itertools
的另一种方式:
from operator import sub # function for subtraction
from more_itertools import flatten, pairwise
list(flatten(t for t in pairwise(test) if sub(*t)==-1))
gives 给
[1, 2, 3, 4, 4, 5, 6, 7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.