Python:查找列表对的一个成员中的连续变化,报告其他成员
必须有一种更简单、更Python 的方法来做到这一点。
给定这个对列表:
pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]
如何最轻松地找到相邻对中第二个项目发生变化的第一个项目(此处从 1 到 2)。因此我正在寻找 ['c','d']。假设整个列表的pair[1]中只有一个变化,但它可能是一个字符串。
这段代码可以工作,但看起来非常长且麻烦。
for i, pair in enumerate(pp):
if i == 0:
pInitial = pair[0]
sgInitial = pair[1]
pNext = pair[0]
sgNext = pair[1]
if sgInitial == sgNext:
sgInitial = sgNext
pInitial = pNext
else:
pOne = pInitial
pTwo = pNext
x = [pOne, pTwo]
print x
break
谢谢 蒂姆
There must be a simpler, more pythonic way of doing this.
Given this list of pairs:
pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]
How do I most easily find the first item in adjacent pairs where the second item changes (here, from 1 to 2). Thus I'm looking for ['c','d']. Assume there will only be one change in pair[1] for the entire list, but that it may be a string.
This code works but seems excruciatingly long and cumbersome.
for i, pair in enumerate(pp):
if i == 0:
pInitial = pair[0]
sgInitial = pair[1]
pNext = pair[0]
sgNext = pair[1]
if sgInitial == sgNext:
sgInitial = sgNext
pInitial = pNext
else:
pOne = pInitial
pTwo = pNext
x = [pOne, pTwo]
print x
break
Thanks
Tim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
添加了我的可读生成器版本。
Added my readable generator version.
您可以尝试类似的方法:(
使用列表理解)
You could try somethingl like :
(using list comprehension)
尝试将
pp[:-1]
与pp[1:]
进行比较,例如(查看
zip(pp[:-1], pp[1: ])
首先看看编辑发生了什么:
我想你需要
try comparing
pp[:-1]
topp[1:]
, something like(look at
zip(pp[:-1], pp[1:])
first to see what's going onedit:
i guess you'd need
这是递归的东西(简单?):
Here is something (simple?) with recursion:
为了清晰起见,我喜欢这样......如果您发现列表理解清晰的话。它确实创建了两个临时列表:pp[1:] 和 zip() 结果。然后它会比较所有相邻对并给出它发现的第一个更改。
这个看起来类似的生成器表达式不会创建临时列表,并在到达第一个更改时停止处理:
此页面上的每个人的示例都比您想要捕获错误时的示例更紧凑。
I like this for clarity...if you find list comprehensions clear. It does create two temporary lists: pp[1:] and the zip() result. Then it compares all the adjacent pairs and gives you the first change it found.
This similar-looking generator expression doesn't create temporary lists and stops processing when it reaches the first change:
Everybody's examples on this page are more compact than they would be if you wanted to catch errors.