如何在Python中递归地将列表元素“向下”移动到另一个列表的相应元素?

时间:2011-11-15 03:43:41

标签: python nested-lists

我有一个6元素列表的列表。如果嵌套列表的两个特定“列”不匹配,我想以递归方式将前3个元素“移位”到顶部列表长度的下一个列表中......所以:

list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'], 
    ['4', 'what', '3', '0', 'and', '2'], 
    ['4', 'is', '2', '1', 'what', '3'], 
    ['4', 'the', '2', '1', 'is', '5']
]

变为

list2 =  [
    ['0', 'EOS', '0', '4', 'EOS', '15'], 
    ['4', 'and', '3', '0', 'and', '2'], 
    ['4', 'what', '3', '1', 'what', '3'], 
    ['4', 'is', '2', '1', 'is', '5']
]

最后一个列表的最后3个元素不添加新列表。

我确信有一些内置方法可以做到这一点,但我找不到它。谢谢!

1 个答案:

答案 0 :(得分:0)

我不知道内置,当然也不是非常pythonic,但这有效(修改到位):

list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'], 
    ['4', 'what', '3', '0', 'and', '2'], 
    ['4', 'is', '2', '1', 'what', '3'], 
    ['4', 'the', '2', '1', 'is', '5']
]
prev = ['0','EOS','0']
for i in list1:
    tmp = i[0:3]
    i[0:3] = prev
    prev = tmp

print list1

稍微好一点但仍然丑陋(创建一个新列表):

list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'], 
    ['4', 'what', '3', '0', 'and', '2'], 
    ['4', 'is', '2', '1', 'what', '3'], 
    ['4', 'the', '2', '1', 'is', '5']
]

prev = ['0','EOS','0']
y = [prev + [0,0,0]] + list1
list2 = [y[i][0:3] + list1[i][3:] for i in range(0, len(list1))]

通过添加新数据来修改旧列表,仍然会创建一个新列表:

list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'], 
    ['4', 'what', '3', '0', 'and', '2'], 
    ['4', 'is', '2', '1', 'what', '3'], 
    ['4', 'the', '2', '1', 'is', '5']
]

list1 = [['0','EOS','0']] + list1
print [list1[i-1][0:3] + list1[i][3:] for i in range(1, len(list1))]

这可能是最好的。利用序列[-1]的行为,创建一个新列表:

list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'], 
    ['4', 'what', '3', '0', 'and', '2'], 
    ['4', 'is', '2', '1', 'what', '3'], 
    ['4', 'the', '2', '1', 'is', '5']
]

# Put the new data on the end of the list
list1[-1][0:3] = ['0','EOS','0']
# note how i=0 -1 references the *last* element of the list
print [list1[i-1][0:3] + list1[i][3:] for i in range(0, len(list1))]