Python/编程新手在这里,试图弄清楚这个while循环发生了什么。首先是代码:
var_list = []
split_string = "pink penguins,green shirts,blue jeans,fried tasty chicken,old-style boots"
def create_variations(split_string):
init_list = split_string.split(',')
first_element = init_list[0]
# change first element of list to prepare for while loop iterations
popped = init_list.pop()
added = init_list.insert(0, popped)
while init_list[0] != first_element:
popped = init_list.pop()
added = init_list.insert(0, popped)
print init_list # prints as expected, with popped element inserted to index[0] on each iteration
var_list.append(init_list) # keeps appending the same 'init_list' as defined on line 5, not those altered in the loop!
print var_list
create_variations(split_string)
我的目标是创建 的所有变体init_list
,这意味着索引被旋转,以便每个索引都成为第一个。然后将这些变体附加到另一个列表中,该列表var_list
在此代码中。
但是,我没有从 while 循环中得到我期望的结果。在 while 循环中,这段代码print init_list
实际上打印了我想要的变体;但是下一行代码var_list.append(init_list)
没有附加这些变体。相反,init_list
在第 5 行创建的 as 被重复附加到var_list
.
这里发生了什么?以及如何init_list
将 while 循环中创建的不同变体附加到var_list
.
我期望的输出var_list
:
[['fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts', 'blue jeans'],
['blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins', 'green shirts'],
['green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots', 'pink penguins'],
['pink penguins', 'green shirts', 'blue jeans', 'fried tasty chicken', 'old-style boots']]