0

I am trying to iterate two successive elements of the list of lists.

     mentionedlist=[[1,2,3,4][1,2,3,4][2,3,4,5][3,4,5,5][1,2,3,4][1,2,3,4][]]

Now I want to compare weather first element of a list in mentionedlist and first element of next list in mentionedlist is same, I also want to do these comparision throughout the list.

 [1,2,3,4][1,2,3,4] is example of answer that i am expecting.
4

2 回答 2

1

注意:您还需要在列表中的值之间放置逗号,即List=[[1,..],[2,..]]

from itertools import islice
mentionedList=[[1,2,3,4],[1,2,3,4],[2,3,4,5],[3,4,5,5],[1,2,3,4],[1,2,3,4],[]]
for i,v in enumerate(islice(mentionedList,0,len(mentionedList)-1)):
    print (v,mentionedList[i+1])

给你:

([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [2, 3, 4, 5])
([2, 3, 4, 5], [3, 4, 5, 5])
([3, 4, 5, 5], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [])

使用这种方法,您不需要制作列表的副本。

于 2013-05-04T02:26:38.690 回答
1

你可以这样做,以获得连续的元素:

mentionedlist=[[1,2,3,4],[1,2,3,4],[2,3,4,5],[3,4,5,5],[1,2,3,4],[1,2,3,4],[]]
for l1, l2 in zip(mentionedlist, mentionedlist[1:]):
    print l1, l2

输出

[1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] [2, 3, 4, 5]
[2, 3, 4, 5] [3, 4, 5, 5]
[3, 4, 5, 5] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] []

要进行成对比较:

for l1, l2 in zip(mentionedlist, mentionedlist[1:]):
    if len(l1) == len(l2) and sum(x != y for x,y in zip(l1, l2)) == 0:
        print l1, l2

这给了你:

[1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4]
于 2013-05-04T02:14:51.507 回答