Python:在列表对的一个成员中查找顺序更改,然后报告其他 [英] Python: find sequential change in one member of list pairs, report other
本文介绍了Python:在列表对的一个成员中查找顺序更改,然后报告其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
必须有一种更简单,更Python化的方式来做到这一点.
There must be a simpler, more pythonic way of doing this.
给出以下配对列表:
pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]
我如何最轻松地在第二对项目发生变化的相邻对中找到第一项(这里是从1到2).因此,我正在寻找['c','d'].假设整个列表的pair [1]中只有一个更改,但是它可能是字符串.
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
谢谢 蒂姆
推荐答案
import itertools as it
pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]
# with normal zip and slicing
for a,b in zip(pp,pp[1:]):
if a[1] != b[1]:
x=(a[0],b[0])
print x
break
# with generators and izip
iterfirst = (b for a,b in pp)
itersecond = (b for a,b in pp[1:])
iterfirstsymbol = (a for a,b in pp)
itersecondsymbol = (a for a,b in pp[1:])
iteranswer = it.izip(iterfirstsymbol, itersecondsymbol, iterfirst, itersecond)
print next((symbol1, symbol2)
for symbol1,symbol2, first, second in iteranswer
if first != second)
添加了可读的生成器版本.
Added my readable generator version.
这篇关于Python:在列表对的一个成员中查找顺序更改,然后报告其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文