这里的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))
这给了我我希望的产出:
There are 10 entries with 4 sequential events and 5 non-sequentual events
[1, 2, 3, 4, 4, 5, 6, 7]
我更喜欢毕多尼奥尼亚,我试图用地图和拉链来重现这个画面:
map(diff_val(help_here_pls), zip(test, test[1:]))
我知道映射遵循“map(函数,可迭代)”。如何使我的地图输出与我喜欢的
[1, 2, 3, 4, 4, 5, 6, 7]
使用一个函数( help_here_pls")。
我知道:
我是否通过地图中的函数传递元组?lambda能处理这个问题吗?还是我需要定义一个单独的函数?即使我能做到这一点,我也必须打开元组吗?(i,j) =传递的元组
谢谢您能提供的任何指导!欢迎阅读/参考资料!
发布于 2017-08-02 19:16:14
清单理解是这里的节奏曲选择。我更改了结果,给出了一个元组列表,因为扁平的列表模糊了每一对项之间的关系。
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)
输出:
There are 10 entries with 4 sequential events and 5 non-sequentual events
[(1, 2), (3, 4), (4, 5), (6, 7)]
下面是另一种使用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))
给出
[1, 2, 3, 4, 4, 5, 6, 7]
https://stackoverflow.com/questions/45466936
复制相似问题