我还在学习python,并尝试使用循环移动列表中的值。但不知道该怎么做。
示例列表我有(6和8个值):
lst1 = [[1,2,3,4,5,6],[],[]]
lst2 = [[1,2,3,4,5,6,7,8],[],[]]
我想移动' 1'到lst1 [1] [0],这将成为:
lst1 = [[2,3,4,5,6],[1],[]]
但我不知道怎么用命令来做。我最好将它放在一个函数中,这样我就可以使用更多变量,例如包含9,10,11等数字的列表。
答案 0 :(得分:2)
这是一种方法:
In [11]: lst1 = [[1,2,3,4,5,6],[],[]]
In [12]: lst1[1].append(lst1[0].pop(0))
In [13]: lst1
Out[13]: [[2, 3, 4, 5, 6], [1], []]
在这里,lst1[0].pop(0)
" pops" lst1[0]
的第0个元素,并将其附加到lst1[1]
。
将此功能转换为功能留给读者练习。 : - )
答案 1 :(得分:0)
以下是将其转换为函数的方法:
#this makes the function
def move_the_numbers():
lst1 = [[1,2,3,4,5,6],[],[]]
lst2 = [[1,2,3,4,5,6,7,8],[],[]]
#this moves the number and appends it to the correct space in the list
lst1[1].append(lst1[0].pop(0))
print lst1
#this calls the function
move_the_numbers()