我正在尝试迭代列表列表中的两个连续元素。
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][]]
现在我要比较提到的列表中列表的天气第一个元素和提到的列表中下一个列表的第一个元素是相同的,我也想在整个列表中进行这些比较。
[1,2,3,4][1,2,3,4] is example of answer that i am expecting.
答案 0 :(得分: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]
答案 1 :(得分: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], [])
使用此方法,您无需复制列表。