当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I shift list elements "down" to corresponding elements of another list recursively in Python?

问题描述:

I have a list of 6-element lists. If two particular "columns" of the nested list don't match, I want to recursively "shift" the first 3 elements to the next list for the length of the top list... So:

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']

]

becomes

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']

]

where the last 3 elements of the last list don't add a new list.

I'm sure there's some built-in way to do this, but I can't find it. Thanks!

网友答案:

I don't know about built-in, and certainly not terribly pythonic, but this works (modifies in place):

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

A little better but ugly still (creates a new list):

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))]

Modifies the old list by prepending the new data, still creates a new list:

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))]

This might be the best. Takes advantage of the behavior of sequence[-1], creates a new list:

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))]
分享给朋友:
您可能感兴趣的文章:
随机阅读: