【发布时间】:2017-08-02 17:03:35
【问题描述】:
这里是 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]
我更喜欢 Pythonic,我正在尝试使用 map 和 zip 重新创建它:
map(diff_val(help_here_pls), zip(test, test[1:]))
我知道地图遵循“地图(函数,可迭代)”。如何让我的地图输出与我的首选列表相匹配
[1, 2, 3, 4, 4, 5, 6, 7]
使用函数(help_here_pls")。
我知道:
- zip 创建一个元组列表
- map 采用函数和可迭代(在本例中来自我的 zip)
我是否通过 map 中的函数传递一个元组? lambda 可以处理这个,还是我需要定义一个单独的函数?即使我能做到这一点,我是否必须解包元组? (i ,j) = [通过的元组]
提前感谢您提供的任何指导!欢迎阅读/参考!
【问题讨论】:
-
列表理解最好在这里:
[n for tup in zip(test, test[1:]) for n in tup if tup[1]-tup[0] == 1]。虽然我更喜欢显示我有成对数字的结果,所以我会做[(i,j) for (i,j) in zip(test, test[1:]) if j-i == 1]给[(1, 2), (3, 4), (4, 5), (6, 7)] -
当我运行你的例子时,我得到
There are 10 entries with 4 sequential events and 1 non-sequentual events [1, 2, 2, 1, 1, 3, 3, 4, 4, 4, 4, 5, 5, 2, 2, 6, 6, 7] -
@jacoblaw 我正在使用 python 3.4.3 在 C9.io 上运行。不知道那里发生了什么。
标签: python python-3.x dictionary lambda zip